如何在Plotly with subplot中消除重复的图例(Python)?

wmvff8tz  于 4个月前  发布在  Python
关注(0)|答案(1)|浏览(60)

下面的代码生成2 plotly图表,并将它们放置在子图中。每个子图包含与另一个子图部分重叠的图例。因此,右边有重复的图例。有人知道在这种情况下消除重复图例的更好方法吗?谢谢。

import plotly.graph_objects as go
from plotly.subplots import make_subplots

f1 = go.Figure([
    go.Scatter(x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5], name="A"),
    go.Scatter(x=[1, 2, 3, 4, 5], y=[5, 4, 3, 2, 1], name="B")
])
f2 = go.Figure([
    go.Scatter(x=[1, 2, 3, 4, 5], y=[1, 2, 5, 4, 5], name="B"),
    go.Scatter(x=[1, 2, 3, 4, 5], y=[5, 4, 1, 2, 1], name="C")
])

fig = make_subplots(rows=1, cols=2, subplot_titles=['F1', 'F2'])

for ea in f1.data:
    fig.add_trace(ea, row=1, col=1)
    
for ea in f2.data:
    fig.add_trace(ea, row=1, col=2)
    
fig.show()

字符串


的数据

zwghvu4y

zwghvu4y1#

可能有几种方法可以做到这一点,但最简单的是设置第二个图形来指定颜色并隐藏图例。

import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(rows=1, cols=2, subplot_titles=['F1', 'F2'])

fig.add_trace(go.Scatter(x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5], name="A", legendgroup='A'), row=1, col=1)
fig.add_trace(go.Scatter(x=[1, 2, 3, 4, 5], y=[5, 4, 3, 2, 1], name="B", legendgroup='B'), row=1, col=1)

fig.add_trace(
    go.Scatter(
        x=[1, 2, 3, 4, 5],
        y=[1, 2, 5, 4, 5],
        line=go.scatter.Line(color='#EF553B'),
        name="B",
        legendgroup='B',
        showlegend=False
    ), row=1, col=2)
fig.add_trace(
    go.Scatter(
        x=[1, 2, 3, 4, 5],
        y=[5, 4, 1, 2, 1],
        line=go.scatter.Line(color='#00cc96'),
        name="C",
        legendgroup='C',
        showlegend=True
    ), row=1, col=2)

fig.show()

字符串


的数据
图例“B”切换


相关问题