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

如何为Plotly堆叠条形图的每个系列设置统一颜色?

解决Plotly堆叠条形图系列颜色统一设置问题

你当前代码里的plot.update_traces(marker_color=[...])是把颜色列表按每个数据点依次分配给所有条形,而非给每个系列(每个go.Bar)分配单一颜色,这就导致同一个年龄组的不同系列条形被设成了列表里的颜色,进而图例和条形颜色不匹配。

以下是两种可行的解决方案:

方法1:给每个go.Bar单独设置统一颜色

直接在每个go.Bar对象中添加marker_color参数,指定该系列的专属颜色:

x = ['18-25', '25-35', '35-45','45-55','55-65']

plot = px.Figure(data=[
           go.Bar(
               name='Bulle de Babel',
               x=x,
               y=[97, 204, 192, 145, 96],
               marker_color='#FDCCFF'
           ),
           go.Bar(
               name='Maniet',
               x=x,
               y=[30, 73, 85, 80, 43],
               marker_color='#0F22FA'
           ),
          go.Bar(
              name='iPhone',
              x=x,
              y=[165, 127, 143, 107, 86],
              marker_color='#D73E0F'
          ),
          go.Bar(
              name='hey',
              x=x,
              y=[115, 99, 92, 92, 31],
              marker_color='#ffd700'
          ),
          go.Bar(
              name='usg',
              x=x,
              y=[64, 59, 51, 29, 23],
              marker_color='#707070'
          )
    ])
                                         
plot.update_layout(barmode='stack') 
plot.show()

方法2:用update_traces配合selector批量设置系列颜色

如果不想逐个修改go.Bar,可以通过selector匹配系列名称,单独设置颜色:

x = ['18-25', '25-35', '35-45','45-55','55-65']

plot = px.Figure(data=[
           go.Bar(name='Bulle de Babel', x=x, y=[97, 204, 192, 145, 96]),
           go.Bar(name='Maniet', x=x, y=[30, 73, 85, 80, 43]),
           go.Bar(name='iPhone', x=x, y=[165, 127, 143, 107, 86]),
           go.Bar(name='hey', x=x, y=[115, 99, 92, 92, 31]),
           go.Bar(name='usg', x=x, y=[64, 59, 51, 29, 23])
    ])
                                         
plot.update_layout(barmode='stack') 

# 按系列名称匹配设置颜色
plot.update_traces(marker_color='#FDCCFF', selector=dict(name='Bulle de Babel'))
plot.update_traces(marker_color='#0F22FA', selector=dict(name='Maniet'))
plot.update_traces(marker_color='#D73E0F', selector=dict(name='iPhone'))
plot.update_traces(marker_color='#ffd700', selector=dict(name='hey'))
plot.update_traces(marker_color='#707070', selector=dict(name='usg'))

plot.show()

两种方法都能让每个系列的所有条形使用统一颜色,图例颜色也会和对应系列的条形完全匹配,达成你期望的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:25:44