You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly go.Bar子图:添加按material分类的颜色共享图例

为Plotly子图柱状图添加共享颜色图例

你当前的代码是把同一子图内的所有柱状条作为单个trace添加,导致Plotly无法生成对应每个material的图例项。要实现共享图例,需要将每个material对应的柱状条单独拆分为一个trace,并且统一每个material的名称和颜色,Plotly会自动将同名同色的trace合并为共享图例。

修改后的完整代码

materials=['food', 'flowers', 'chess', 'garden', 'kitchen']
x=['browns', 'highes', 'jacks', 'johns', 'harrys']
y=[1,3,5,6,7]
x2=['trevors', 'elens', 'georges', 'marias', 'franks']
y2=[3,7,8,9,5]
fig = make_subplots(rows=3, cols=1)
color_map = {'food':'red',
      'flowers':'blue',
      'chess':'yellow',
      'garden':'green',
      'kitchen':'grey'}

# 第一个子图:逐个添加每个material对应的柱状条
for mat, xi, yi in zip(materials, x, y):
    fig.add_trace(
        go.Bar(
            x=[xi],
            y=[yi],
            name=mat,  # 图例名称与material绑定
            marker_color=color_map[mat],
            showlegend=True  # 仅在第一个子图显示图例
        ),
        row=1, col=1
    )

# 第二个子图:同样逐个添加,关闭图例重复显示
for mat, xi, yi in zip(materials, x2, y2):
    fig.add_trace(
        go.Bar(
            x=[xi],
            y=[yi],
            name=mat,  # 保持与第一个子图相同的name,自动关联共享图例
            marker_color=color_map[mat],
            showlegend=False
        ),
        row=2, col=1
    )

fig.show()

核心要点

  • 拆分独立trace:不再一次性添加所有柱状条,而是循环遍历每个material,单独创建对应的trace,让每个trace对应一个图例项。
  • 统一标识规则:每个material对应的trace使用相同的name和marker_color,Plotly会自动识别这些属于同一类别,合并为共享图例。
  • 控制图例重复:第一个子图的trace开启showlegend=True,后续子图关闭该参数,避免图例多次显示。

内容的提问来源于stack exchange,提问作者Niam45

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 06:41:00