如何让Plotly Python子图中对应数据使用相同颜色与统一图例?
解决Plotly子图同名Trace颜色不一致与图例统一问题
要同时解决子图中同名trace颜色不统一、图例独立的问题,核心是利用Plotly的legendgroup参数将同名trace归为同一图例组,再配合showlegend控制图例显示逻辑,具体实现如下:
修改后的代码
import plotly.graph_objects as go from plotly.subplots import make_subplots fig = make_subplots(rows=2, cols=1) # 第一行子图的blue trace:设置图例组,且显示图例 fig.add_trace(go.Bar(name="blue", x=["a","b"], y=[1,2], legendgroup="blue", showlegend=True), row=1, col=1) # 第一行子图的red trace:设置图例组,且显示图例 fig.add_trace(go.Bar(name="red", x=["a","b"], y=[3,1], legendgroup="red", showlegend=True), row=1, col=1) # 第二行子图的blue trace:同组,不显示重复图例 fig.add_trace(go.Bar(name="blue", x=["a","b"], y=[2,3], legendgroup="blue", showlegend=False), row=2, col=1) # 第二行子图的red trace:同组,不显示重复图例 fig.add_trace(go.Bar(name="red", x=["a","b"], y=[1,4], legendgroup="red", showlegend=False), row=2, col=1) fig.update_layout(height=600, width=400, showlegend=True) fig.show()
关键逻辑说明
legendgroup:将同名的trace设置为相同的图例组名称,Plotly会自动为同组trace分配一致的颜色,且点击图例时会同步控制所有同组trace的显示/隐藏。showlegend:仅让每个图例组的第一个trace显示图例(设为True),其余同组trace设为False,避免生成重复图例,实现图例统一。
这样修改后,既保证了同名trace颜色完全一致,又合并了独立的图例,达到预期效果。
内容的提问来源于stack exchange,提问作者ambrustorok
相关产品推荐
相关产品推荐

