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')无法匹配到第二层的子标签,所以需要通过为每个数据点指定颜色来实现需求。
实现步骤
- 遍历第二层分类标签,为"Gross Income"项设置目标绿色,其他项保留默认颜色(EBITDA作为
total类型,Plotly会自动应用特殊样式)。 - 将生成的颜色列表传入瀑布图的
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
相关产品推荐
相关产品推荐

