【问题标题】:How to set different colors for bars in a plotly waterfall chart?如何在情节瀑布图中为条形设置不同的颜色?
【发布时间】:2020-10-10 15:59:04
【问题描述】:

我有一个瀑布图,我想分别设置每个条的颜色(第一个为蓝色,第二个、第三个和第四个为红色,第五个为绿色,第六个为蓝色)。图表中的所有相关条都在增加,而 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()

结果:

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

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

【问题讨论】:

    标签: python plotly


    【解决方案1】:

    问题

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

    解决方案

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

    • increasing 属性中设置标记颜色为红色
    • totals 属性中设置标记颜色为蓝色
    • 通过.add_shape()将蓝色和绿色的形状添加到第 1 和第 4 条
    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()
    

    这会产生 OP 想要的结果

    参考

    【讨论】:

      猜你喜欢
      • 2020-03-13
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多