如何在plotly瀑布图中为条形图设置不同的颜色?

2024-05-31 23:38:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个瀑布图,我想分别设置每个条的颜色(第一条为蓝色,第二条、第三条和第四条为红色,第五条为绿色,第六条为蓝色)。图表中的所有相对条形图都在增加,plotly仅允许您为增加、减少和总计设置三种颜色。 有什么办法可以满足我的要求吗

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()

结果: enter image description here

正如我所说,我希望酒吧的颜色是:

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


Tags: andthegofor颜色figblueplotly
1条回答
网友
1楼 · 发布于 2024-05-31 23:38:39

问题

Ploty瀑布图条形图颜色自定义。正如OP提到的,当前plotly支持自定义条颜色以减少、增加和总计

解决方案

在OP的示例中,要制作条的颜色(蓝色、红色、红色、红色、绿色、蓝色):

  • increasing属性中设置标记颜色红色
  • totals属性中设置标记颜色蓝色
  • 通过.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()

这将产生我们想要的结果 waterfall plot with color the op wanted

参考文献

相关问题 更多 >