简体   繁体   中英

How to set different colors for bars in a plotly waterfall chart?

I have a waterfall chart and I want to set each bar's color separately (blue for the first one, red for the 2nd, 3rd, and 4th one, green for 5th one, and blue for 6th one). All the relative bars in the chart are increasing, and the plotly only allows you to set three colors for increasing, decreasing, and total ones. Is there any way to do what I want?

import plotly.graph_objects as go

fig = go.Figure(go.Waterfall(
    name = "20", orientation = "v",
    measure = ["relative", "relative", "relative", "relative", "relative", "total"],
    x = ["Buy", "Transaction Cost", "Remodeling Cost", "Ownership Cost", "Gain", "Sell"],
    textposition = "outside",
    text = ["$200", "$14", "$45", "$5", "$86", "$350"],
    y = [200, 14, 45, 5, 86, 350],
    connector = {"visible": False}
))
fig.show()

Result: 在此处输入图像描述

As I said, I want the color of the bar to be:

blue for the first one, red for the 2nd, 3rd, and 4th one, green for 5th one, and blue for 6th one

Problem

Ploty waterfall chart bar color customization. As OP mentioned, currently plotly supports customizing bar colors for decreasing, increasing, and totals.

Solution

In OP's example, to make color of bars (blue, red, red, red, green, blue):

  • set marker color red in increasing attribute
  • set marker color blue in totals attribute
  • add shapes of blue and green to the 1st and 4th bar via .add_shape()
import plotly.graph_objects as go

fig = go.Figure(go.Waterfall(
    name = "20", orientation = "v",
    measure = ["relative", "relative", "relative", "relative", "relative", "total"],
    x = ["Buy", "Transaction Cost", "Remodeling Cost", "Ownership Cost", "Gain", "Sell"],
    textposition = "outside",
    text = ["$200", "$14", "$45", "$5", "$86", "$350"],
    y = [200, 14, 45, 5, 86, 350],
    increasing = {"marker":{"color":"red"}},
    totals = {"marker":{"color":"blue"}},
    connector = {"visible": False}
))

fig.add_shape(
    type="rect", fillcolor="blue", line=dict(color="blue"), opacity=1,
    x0=-0.4, x1=0.4, xref="x", y0=0.0, y1=fig.data[0].y[0], yref="y"
)

fig.add_shape(
    type="rect", fillcolor="green", line=dict(color="green"), opacity=1,
    x0=3.6, x1=4.4, xref="x",
    y0=fig.data[0].y[-1] - fig.data[0].y[-2], y1=fig.data[0].y[-1], yref="y"
)

fig.show()

Which would yield the result OP wanted带有 op 想要的颜色的瀑布图

Reference

I know this is an old question. But I keep running into it and having issues applying the shape when each marker is dynamic. So I figured out a way to handle this with css.

g.point:nth-of-type(1) path {
fill: blue !important;
stroke: blue !important;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM