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

Plotly Dash柱状图自动配色设置求助:替换统一蓝色样式

解决方案:给Dash(Plotly)柱状图的每个柱子设置不同颜色

Hey there! Let's get those bars looking colorful instead of all blue—super easy to fix with just a small addition to your code. Here's what you need to do:

核心思路

Plotly的go.Bar对象支持通过marker=dict(color=...)参数为每个柱子指定单独的颜色。你可以用Plotly内置的调色板,或者自定义颜色列表,只要颜色数量和柱子数量匹配就行。

修改后的完整代码

import plotly.colors as pc
import pandas as pd
import plotly.graph_objects as go
import dash_core_components as dcc
import dash_html_components as html

# 假设你的df数据已经准备好
pv = pd.pivot_table(df, index=['customer_name2'], columns=['FY'], values=['amount'], aggfunc=sum, fill_value=0)
pv2 = pv.reindex(pv['amount'].sort_values(by='FY17', ascending=True).index).head(x_bottom)

# 生成与柱子数量匹配的颜色列表 - 用Plotly内置的定性调色板
color_list = pc.qualitative.Alphabet[:len(pv2.index)]

trace1 = go.Bar(
    x=pv2.index,
    y=pv2[('amount','FY17')],
    name='Revenue',
    marker=dict(color=color_list)  # 关键:添加这一行实现多色柱子
)

graphs.append(html.Div(
    dcc.Graph(
        id='chart_id_6',
        figure={
            'data': [trace1],
            'layout': {
                'title': 'Bottom ' + str(x_bottom) + ' Customers'
            }
        }
    )
))

细节说明

  • 内置调色板:pc.qualitative.Alphabet是Plotly提供的一套现成的区分度高的颜色,我们取前len(pv2.index)个颜色,刚好对应每个柱子。还有其他内置调色板比如pc.qualitative.D3、pc.qualitative.Pastel1,你可以根据喜好替换。
  • 自定义颜色:如果你想自己选颜色,直接定义一个颜色列表就行,比如:
    color_list = ['#FF5733', '#33FF57', '#3357FF', '#FF33A6', '#FFC300']
    
    只要列表长度和你的柱子数量一致,每个柱子就会按顺序对应颜色。

这样修改后,你的柱状图就会每个柱子都有不同的颜色啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:52:16