Plotly子图如何实现相同数据、名称及图例统一?
关于Plotly子图中复用数据、名称和图例的问题解答
可以在Plotly不同子图中复用相同名称的图例,且保证对应颜色完全一致,核心是通过legendgroup参数将同名trace归为同一组,同时用showlegend控制图例仅显示一次,避免重复。
你的代码问题分析
- 数据引用错误:多个trace的
y值错误引用了df['A'],比如标注为B的trace实际应使用df['B'],标注为C的trace应使用df['C'],这会导致数据展示完全错误。 - 图例分组缺失:未设置
legendgroup参数,导致同名trace被视为独立分组,Plotly会自动分配新颜色,最终造成同名称元素颜色不一致的问题。
修正后的代码
import pandas as pd from plotly.subplots import make_subplots import plotly.graph_objects as go # 样本数据 data = { 'year': [2000, 2001, 2002, 2003, 2004], 'A': [1, 3, 2, 5, 4], 'B': [2, 4, 1, 6, 3], 'C': [3, 2, 4, 3, 2], 'D': [4, 3, 5, 2, 1] } df = pd.DataFrame(data) # 预定义各名称对应颜色 colors = {'A': 'blue', 'B': 'orange', 'C': 'green', 'D': 'red'} # 创建子图 fig = make_subplots(rows=1, cols=2, subplot_titles=['Stacked Area A-B', 'Stacked Area C-D']) # 第一个子图:添加A和B的堆叠面积图 fig.add_trace( go.Scatter( x=df['year'], y=df['A'], fill='tozeroy', name='A', stackgroup='one', line_color=colors['A'], legendgroup='A', # 标记为A组 showlegend=True # 显示该组图例 ), row=1, col=1) fig.add_trace( go.Scatter( x=df['year'], y=df['B'], fill='tonexty', name='B', stackgroup='one', line_color=colors['B'], legendgroup='B', showlegend=True ), row=1, col=1) # 第二个子图:添加C和A的堆叠面积图 fig.add_trace( go.Scatter( x=df['year'], y=df['C'], fill='tozeroy', name='C', stackgroup='one', line_color=colors['C'], legendgroup='C', showlegend=True ), row=1, col=2) fig.add_trace( go.Scatter( x=df['year'], y=df['A'], fill='tonexty', name='A', stackgroup='one', line_color=colors['A'], legendgroup='A', # 和第一个A归为同一组 showlegend=False # 不重复显示图例 ), row=1, col=2) # 更新坐标轴标签 fig.update_xaxes(title_text='Year', row=1, col=1) fig.update_yaxes(title_text='Value', row=1, col=1) fig.update_xaxes(title_text='Year', row=1, col=2) fig.update_yaxes(title_text='Value', row=1, col=2) # 更新布局 fig.update_layout(showlegend=True, hovermode='x', title='Stacked Area Subplots') fig.show()
关键配置说明
legendgroup:将相同名称的trace设置为同一组,确保颜色和图例联动,同一组的元素自动使用相同颜色。showlegend:仅在第一次添加同名trace时设为True,后续重复添加时设为False,避免图例重复出现。- 手动指定
line_color:进一步强制固定颜色,避免Plotly自动分配颜色导致的不一致。
内容的提问来源于stack exchange,提问作者Bruno Peixoto
相关产品推荐
相关产品推荐

