如何消除Plotly子图中的重复图例(Python)
解决Plotly子图重复图例的问题
当使用Plotly子图布局时,若不同子图包含相同名称的trace,会导致右侧出现重复图例。以下是两种有效的解决方法:
原始问题代码
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()
重复图例效果:
方法一:自动去重图例
通过记录已出现的图例名称,仅保留每个名称的第一次显示,后续同名trace隐藏图例:
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']) seen_names = set() # 添加第一个子图的trace for ea in f1.data: if ea.name not in seen_names: seen_names.add(ea.name) else: ea.showlegend = False fig.add_trace(ea, row=1, col=1) # 添加第二个子图的trace for ea in f2.data: if ea.name not in seen_names: seen_names.add(ea.name) else: ea.showlegend = False fig.add_trace(ea, row=1, col=2) fig.show()
方法二:使用图例分组(推荐)
通过legendgroup将同名trace归为一组,手动设置仅显示一次图例,同时保证点击图例时同组trace联动:
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", legendgroup="A"), go.Scatter(x=[1,2,3,4,5], y=[5,4,3,2,1], name="B", legendgroup="B") ]) f2 = go.Figure([ # 同名trace隐藏图例,指定同一图例组 go.Scatter(x=[1,2,3,4,5], y=[1,2,5,4,5], name="B", legendgroup="B", showlegend=False), go.Scatter(x=[1,2,3,4,5], y=[5,4,1,2,1], name="C", legendgroup="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()
内容的提问来源于stack exchange,提问作者Scoodood
相关产品推荐
相关产品推荐

