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

如何用Plotly定制分组柱状图中每组的首列颜色?

解决Plotly分组柱状图单一系列颜色定制问题

你当前的问题核心是:使用px.bar传入多个y列(time_wip和planned_effort)时,Plotly会生成两个独立的trace分别对应这两个数据系列。直接调用fig.update_traces(marker_color=colors)会把颜色规则应用到所有trace上,导致planned_effort系列也被修改了颜色,而你只需要定制第一个系列(time_wip)。

修正方案

只针对第一个trace(对应time_wip)设置颜色,有两种简单可行的方法:

方法1:通过trace索引直接修改

直接定位fig.data中的第一个元素(索引为0),设置它的marker.color:

# 替换原代码中的fig.update_traces(marker_color=colors)
fig.data[0].marker.color = colors

方法2:用update_traces指定selector

使用selector参数筛选目标trace,比如通过名称精准匹配:

fig.update_traces(marker_color=colors, selector=dict(name='time_wip'))

完整修正后的代码

# Create the chart
colors = ['royalblue'] * len(df5)

for i in range(len(df5)):
    if df5['wip_higher'][i] == 0:
        colors[df5.index[i]] = 'palegreen'
    elif df5['wip_higher'][i] == 1:
        colors[df5.index[i]] = 'moccasin'
    elif df5['wip_higher'][i] == 2:
        colors[df5.index[i]] = 'goldenrod'
    elif df5['wip_higher'][i] == 3:
        colors[df5.index[i]] = 'salmon'
    elif df5['wip_higher'][i] == 4:
        colors[df5.index[i]] = 'black'

fig = px.bar(df5,
             x='Issue key',
             y=['time_wip', 'planned_effort'],
             template='plotly_white',
             text_auto=True,
             barmode='group',
             width=1000,
             labels={'y': 'Time in WIP (in Days)',
                     'x': 'Issue Key'}
             )

fig.update_layout(legend=dict(orientation="h",
                              yanchor="bottom",
                              y=1.02,
                              xanchor="right",
                              x=1),
                  legend_title_text='')

# 仅修改time_wip系列的颜色
fig.data[0].marker.color = colors

fig.show()

补充说明

  • 若需要给planned_effort系列设置统一默认颜色,可单独添加一行:
    fig.data[1].marker.color = 'gray' # 自定义第二个系列的颜色
    
  • 可通过打印fig.data查看每个trace的name和属性,确认目标trace的具体信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 10:18:39