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

如何在Plotly分组柱状图中基于RGB值自定义柱体颜色

解决方案

在plotly.graph_objects中自定义分组柱状图颜色,直接在go.Bar中通过marker_color参数传入RGB/RGBA格式的颜色值即可,修改后的完整代码如下:

import plotly.graph_objects as go
class_list = ['class1','class2','class3','class4','class5']
average_length = [10,20,50,30,50]
num_entries = [83,38,83,57,34]

fig = go.Figure(data=[
    # 第一个分组系列指定颜色,这里用你注释里对应的RGB值
    go.Bar(name='Average Cars Per Area', x=class_list, y=average_length, 
           marker_color='rgba(239, 58, 76, 1)'),
    # 第二个分组系列指定颜色
    go.Bar(name='Cars Per Length', x=class_list, y=num_entries, 
           marker_color='rgba(62, 193, 205, 1)'),
])
# 开启分组柱状图模式
fig.update_layout(barmode='group')

fig.update_layout(title_text='Average Cars Per Area and Length',
                  title_x=0.1,
                  plot_bgcolor='rgba(0,0,0,0)',
                  paper_bgcolor='rgba(0,0,0,0)',
                  bargap=0.30,
                  bargroupgap=0.0,
                  margin=dict(l=50, r=50, t=50, b=50),
                  xaxis_title="Score Class",
                  yaxis_title="Gene Length/Number of Proteins",
                  yaxis = dict(
                  tickfont = dict(size=13)),
                  xaxis = dict(
                  tickfont = dict(size=13)),)

fig.update_xaxes(showline=True, linewidth=2, linecolor='black')
fig.update_yaxes(showline=True, linewidth=2, linecolor='black')

fig.show()

补充说明

  • 若需要为同一个系列下不同x值的柱子设置不同颜色,直接给marker_color传入和x轴长度一致的颜色列表即可,示例:
go.Bar(name='Average Cars Per Area', x=class_list, y=average_length, 
       marker_color=[
           'rgba(239, 58, 76, 1)',
           'rgba(135, 206, 250, 0.5)',
           'rgba(255, 165, 0, 0.8)',
           'rgba(128, 0, 128, 0.7)',
           'rgba(0, 128, 0, 0.6)'
       ])
  • 你之前注释的方案失效原因:color_discrete_map是plotly.express绘图接口的专属参数,不适用于go.Bar写法;未加筛选条件直接调用fig.update_traces会覆盖所有系列的颜色配置,无法实现分组系列分别配色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:54:00