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

Plotly瀑布图修改Gross Income项颜色问题求助

问题:Plotly瀑布图修改指定项颜色

我用Plotly创建了包含三类数据的瀑布图,代码如下:

import plotly.graph_objects as go
fig=go.Figure()

fig.add_trace(go.Waterfall(
    x = [["Category 1", "Category 1", "Category 1", "Category 1", "Category 1", "Category 1", "Category 1", 
          "Category 2", "Category 2", "Category 2", "Category 2", "Category 2", "Category 2", "Category 2",
          "Category 3", "Category 3", "Category 3", "Category 3", "Category 3", "Category 3", "Category 3" 
          ],
        ["Gross Income", "Taxes", "Net Revenue", "CPV", "Variable Expenses", "Recurrent Capex", "EBITDA",
         "Gross Income", "Taxes", "Net Revenue", "CPV", "Variable Expenses", "Recurrent Capex", "EBITDA",
         "Gross Income", "Taxes", "Net Revenue", "CPV", "Variable Expenses", "Recurrent Capex", "EBITDA",
         ] 
    ],
    measure = ["absolute", "relative", "relative", "relative", "relative", "relative", "total",
                "absolute", "relative", "relative", "relative", "relative", "relative", "total",
                "absolute", "relative", "relative", "relative", "relative", "relative", "total"
                ],
    y = [
        1693,-296,1501,-897,-27,-45,532,
        1439.05,-251.6,1275.85,-762.44,-22.95,-38.25,452.2,
        1134.31,-198.32,1005.67,-600.99,-18.09,-30.150,356.44
         ]
))

我希望将所有“Gross Income”项的颜色改为绿色,仅让EBITDA保持不同样式。尝试用以下代码修改但未生效:

fig.update_traces(marker_color="LightSeaGreen",selector=dict(x='Gross Income'))

解决方案

因为你的x轴是分层二维结构,selector=dict(x='Gross Income')无法匹配到第二层的子标签,所以需要通过为每个数据点指定颜色来实现需求。

实现步骤

  1. 遍历第二层分类标签,为"Gross Income"项设置目标绿色,其他项保留默认颜色(EBITDA作为total类型,Plotly会自动应用特殊样式)。
  2. 将生成的颜色列表传入瀑布图的marker_color参数。

完整代码示例

import plotly.graph_objects as go
fig=go.Figure()

# 定义数据结构
x_categories = [
    ["Category 1"]*7 + ["Category 2"]*7 + ["Category 3"]*7,
    ["Gross Income", "Taxes", "Net Revenue", "CPV", "Variable Expenses", "Recurrent Capex", "EBITDA"]*3
]
measure_list = ["absolute", "relative", "relative", "relative", "relative", "relative", "total"]*3
y_values = [
    1693,-296,1501,-897,-27,-45,532,
    1439.05,-251.6,1275.85,-762.44,-22.95,-38.25,452.2,
    1134.31,-198.32,1005.67,-600.99,-18.09,-30.150,356.44
]

# 生成颜色列表
color_list = []
for sub_cat in x_categories[1]:
    if sub_cat == "Gross Income":
        color_list.append("LightSeaGreen")
    else:
        color_list.append(None)  # 保留默认颜色

# 创建瀑布图并应用颜色
fig.add_trace(go.Waterfall(
    x = x_categories,
    measure = measure_list,
    y = y_values,
    marker_color = color_list
))

fig.show()

运行上述代码后,所有"Gross Income"项会显示为LightSeaGreen,EBITDA作为total项会保持Plotly默认的差异化样式,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:25:18