带有虚线或虚线边框的 Plotly 条形图 - 如何实现?

Plotly bar chart with dotted or dashed border - How to implement?

我正在尝试创建如下图所示的条形图:

我快完成了,但是我没有找到任何关于设置虚线或点线边框样式的参考资料;

下面是我创建的图表的图片:



我将在下面添加一个最小的可重现代码:

import plotly.graph_objects as go

data={"years":[2019,2020,2021,2022],
      "total_value":[100000000000,220000000000,350000000000,410000000000]}

def bar_styled(data):
    
    blank = 'rgba(0,0,0,0)'
    colors =["#FED241", "#FED241", "#143DCB", blank]

    fig = go.Figure(data=[go.Bar(
        x=data['years'],
        y=data['total_value'],
        marker_color=colors, # marker color can be a single color value or an iterable
        marker_line_width=3
    )])

    fig.update_layout(title_text=None, paper_bgcolor=blank, 
                      height=300, margin={"b":4, "t":4, "l":8, "r":8 })
    
    color_list=fig.data[0]["marker"]["color"]
    
    fig.data[0]["marker"]['line']["color"]=['#FED241' if val == blank else  blank for val in color_list]

    fig.update_xaxes(type='category')
    
    return fig

bar_styled(data)

非常感谢任何关于我如何实现它的参考或帮助;

提前谢谢你们, 问候, 莱昂纳多

根据this Plotly forum post, setting the line style is not possible for bar charts - I looked at the object fig.data[0]["marker"]['line'] which is of type plotly.graph_objs.bar.Marker and there are no properties 可以设置线条的样式。

但是,您可以绘制空白条以显示 x 轴刻度,然后使用 Plotly shapes 在其周围绘制一个具有所需样式的矩形。

当您使用fig.add_shape在条形图上绘制矩形时,第一个条形中心的x坐标为0.0,第二个条形中心为1.0,依此类推on... 这意味着对应于 2022 的条形的中间将位于 x 坐标 3.0.

并且由于条形的默认宽度为 0.8,这意味着您需要在绘制矩形时将 x0 = 2.6, x1 = 3.4 传递给 fig.add_shape。您还可以将矩形的线条样式指定为 dash.

import plotly.graph_objects as go

data={"years":[2019,2020,2021,2022],
      "total_value":[100000000000,220000000000,350000000000,410000000000]}

## this only works if the year occurs once in the data
def get_plotly_xcoordinates(year, width=0.8):
    x_location = data["years"].index(year)
    print(x_location)
    return x_location - width/2, x_location + width/2

def bar_styled(data):
    
    blank = 'rgba(0,0,0,0)'
    colors =["#FED241", "#FED241", "#143DCB", blank]

    fig = go.Figure(data=[go.Bar(
        x=data['years'],
        y=data['total_value'],
        marker_color=colors, # marker color can be a single color value or an iterable
        marker_line_width=3
    )])

    fig.update_layout(title_text=None, paper_bgcolor=blank, 
                      height=300, margin={"b":4, "t":4, "l":8, "r":8 })
    
    # color_list=fig.data[0]["marker"]["color"]
    
    # fig.data[0]["marker"]['line']["color"]=['#FED241' if val == blank else blank for val in color_list]
    x0,x1 = get_plotly_xcoordinates(2022)

    fig.add_shape(type="rect", xref="x", yref="y",
        x0=x0, y0=0,
        x1=x1, y1=410000000000,
        line=dict(color="#FED241",dash="dash",width=3)
    )

    fig.update_xaxes(type='category')
    
    return fig

fig = bar_styled(data)