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

wmvff8tz  于 2024-01-05  发布在  Python
关注(0)|答案(1)|浏览(337)

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

  1. import plotly.graph_objects as go
  2. from plotly.subplots import make_subplots
  3. f1 = go.Figure([
  4. go.Scatter(x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5], name="A"),
  5. go.Scatter(x=[1, 2, 3, 4, 5], y=[5, 4, 3, 2, 1], name="B")
  6. ])
  7. f2 = go.Figure([
  8. go.Scatter(x=[1, 2, 3, 4, 5], y=[1, 2, 5, 4, 5], name="B"),
  9. go.Scatter(x=[1, 2, 3, 4, 5], y=[5, 4, 1, 2, 1], name="C")
  10. ])
  11. fig = make_subplots(rows=1, cols=2, subplot_titles=['F1', 'F2'])
  12. for ea in f1.data:
  13. fig.add_trace(ea, row=1, col=1)
  14. for ea in f2.data:
  15. fig.add_trace(ea, row=1, col=2)
  16. fig.show()

字符串


的数据

zwghvu4y

zwghvu4y1#

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

  1. import plotly.graph_objects as go
  2. from plotly.subplots import make_subplots
  3. fig = make_subplots(rows=1, cols=2, subplot_titles=['F1', 'F2'])
  4. 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)
  5. 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)
  6. fig.add_trace(
  7. go.Scatter(
  8. x=[1, 2, 3, 4, 5],
  9. y=[1, 2, 5, 4, 5],
  10. line=go.scatter.Line(color='#EF553B'),
  11. name="B",
  12. legendgroup='B',
  13. showlegend=False
  14. ), row=1, col=2)
  15. fig.add_trace(
  16. go.Scatter(
  17. x=[1, 2, 3, 4, 5],
  18. y=[5, 4, 1, 2, 1],
  19. line=go.scatter.Line(color='#00cc96'),
  20. name="C",
  21. legendgroup='C',
  22. showlegend=True
  23. ), row=1, col=2)
  24. fig.show()

字符串


的数据
图例“B”切换


展开查看全部

相关问题