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

如何为Plotly堆叠条形图设置自动分配的不同颜色(不使用Plotly Express)

问题原因

当前代码仅添加了1个Bar trace,Plotly默认每个trace使用统一颜色,因此所有堆叠区块颜色完全一致。要实现自动分色,需按堆叠维度(本例为Country字段)拆分数据,每个分类对应一个独立trace,Plotly会自动为不同trace分配默认配色,无需手动指定色值。

修正后可直接运行代码

import pandas as pd
import plotly.graph_objects as go

df2 = pd.DataFrame.from_dict({'Country': {0: 'Europe',
  1: 'America',
  2: 'Asia',
  3: 'Europe',
  4: 'America',
  5: 'Asia',
  6: 'Europe',
  7: 'America',
  8: 'Asia',
  9: 'Europe',
  10: 'America',
  11: 'Asia'},
 'Year': {0: 2014,
  1: 2014,
  2: 2014,
  3: 2015,
  4: 2015,
  5: 2015,
  6: 2016,
  7: 2016,
  8: 2016,
  9: 2017,
  10: 2017,
  11: 2017},
 'Amount': {0: 1600,
  1: 410,
  2: 150,
  3: 1300,
  4: 300,
  5: 170,
  6: 1000,
  7: 500,
  8: 200,
  9: 900,
  10: 500,
  11: 210}})

fig = go.Figure()
# 按国家维度拆分数据,每个国家对应一个独立trace,自动分配不同颜色
for country in df2['Country'].unique():
    country_df = df2[df2['Country'] == country]
    fig.add_trace(go.Bar(x=country_df['Year'], y=country_df['Amount'], name=country))

fig.update_layout(title="Personnel at Work", barmode='stack')
fig.show()

可选配色调整

如果需要更换整套自动分配的配色主题,可在update_layout中添加colorway参数调用Plotly内置色板即可,无需手动指定单个色值,示例:

fig.update_layout(title="Personnel at Work", barmode='stack', colorway=go.colors.qualitative.D3)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:48:02