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

如何在Plotly Express中为Series数据源的柱状图设置自定义颜色

解决Plotly Express柱状图仅单个颜色生效的问题

问题出在你没有指定color参数来区分不同的类别。Plotly Express会把所有柱子视为同一个数据系列,因此只会使用color_discrete_sequence列表中的第一个颜色。

方案1:将Series转为DataFrame并指定类别列

把Series转换为包含类别列和数值列的DataFrame,通过color参数绑定类别列,让Plotly识别每个独立类别:

import pandas as pd
import plotly.express as px

# 将Series转为带列名的DataFrame
df = pd.Series([100,200,300,400],index=['Cat1','Cat2','Cat3','Cat4']).reset_index(name='value')
colors=['green','yellow','red','blue']

fig = px.bar(df, x='index', y='value', color='index', color_discrete_sequence=colors)
fig.show()

方案2:直接绑定color参数为索引

无需转换DataFrame,直接将color参数设置为df.index,让Plotly按索引区分每个柱子:

import pandas as pd
import plotly.express as px

df = pd.Series([100,200,300,400],index=['Cat1','Cat2','Cat3','Cat4'])
colors=['green','yellow','red','blue']

fig = px.bar(x=df.index, y=df, color=df.index, color_discrete_sequence=colors)
fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 07:48:15