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

如何在Python的Plotly柱状图中为每个类别设置颜色

为Plotly柱状图的每个类别设置自定义颜色

下面提供三种实用方法,帮你按Category值为柱状图设置不同颜色:

方法1:自动颜色映射(Plotly Express快速实现)

直接在px.bar中指定color=df['Category'],Plotly会自动为不同类别分配颜色并生成图例:

import plotly.express as px
import pandas as pd

data = {'Index': ['NAGAJAN', 'JORAJAN','KATHALGURI','HEBEDA','MAKUM','BAREKURI','BAGHJAN','Duliajan Area','LANGKASHI','HAPJAN'],
        'Category': [0,5,0,0,2,0, 2,0,0, 2]} 
df = pd.DataFrame(data)

fig = px.bar(df, x='Index', y='Category', color='Category', 
             height=400, width=800, title="Asset Area Vs No of OBS")
fig.update_xaxes(tickangle=90)
fig.update_layout(plot_bgcolor="white")
fig.update_traces(width=0.4)
fig.show()

方法2:自定义颜色映射(指定每个类别的颜色)

创建颜色映射字典,通过color_discrete_map参数传入,完全自定义每个类别的颜色:

import plotly.express as px
import pandas as pd

data = {'Index': ['NAGAJAN', 'JORAJAN','KATHALGURI','HEBEDA','MAKUM','BAREKURI','BAGHJAN','Duliajan Area','LANGKASHI','HAPJAN'],
        'Category': [0,5,0,0,2,0, 2,0,0, 2]} 
df = pd.DataFrame(data)

# 自定义颜色映射:键为Category值,值为对应颜色代码
color_map = {
    0: '#888888',  # 灰色
    2: '#1f77b4',  # 蓝色
    5: '#ff7f0e'   # 橙色
}

fig = px.bar(df, x='Index', y='Category', color='Category', 
             color_discrete_map=color_map,
             height=400, width=800, title="Asset Area Vs No of OBS")
fig.update_xaxes(tickangle=90)
fig.update_layout(plot_bgcolor="white")
fig.update_traces(width=0.4)
fig.show()

方法3:精细控制单个柱子颜色(Graph Objects实现)

如果需要对每一根柱子单独设置颜色,可使用go.Bar生成颜色列表后传入:

import plotly.graph_objects as go
import pandas as pd

data = {'Index': ['NAGAJAN', 'JORAJAN','KATHALGURI','HEBEDA','MAKUM','BAREKURI','BAGHJAN','Duliajan Area','LANGKASHI','HAPJAN'],
        'Category': [0,5,0,0,2,0, 2,0,0, 2]} 
df = pd.DataFrame(data)

# 根据Category值生成对应颜色列表
color_list = []
for cat in df['Category']:
    if cat == 0:
        color_list.append('#888888')
    elif cat == 2:
        color_list.append('#1f77b4')
    elif cat == 5:
        color_list.append('#ff7f0e')

fig = go.Figure(data=[go.Bar(
    x=df['Index'],
    y=df['Category'],
    marker_color=color_list,
    width=0.4
)])
fig.update_layout(
    title="Asset Area Vs No of OBS",
    height=400,
    width=800,
    plot_bgcolor="white"
)
fig.update_xaxes(tickangle=90)
fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:05:32