Plotly柱状图如何实现虚线或点线边框?

4
我正在尝试创建一个条形图,如下图所示: 我想复制的图表 我已经接近成功,但是没有找到有关设置虚线或点线边框样式的参考资料;
下面是我创建的图表图片: 到目前为止我做的图表
我将在下面添加一个最简可复现的代码:
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)

任何有关如何实现这个问题的参考或帮助都会非常感激;
谢谢大家提前, 问候, Leonardo
1个回答

4
根据这个Plotly论坛帖子,对于条形图,设置线条样式是不可能的 - 我查看了对象fig.data [0] ["marker"] ['line'] ,它的类型为plotly.graph_objs.bar.Marker,并且没有属性可以让您设置线条的样式。

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

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

由于默认条的宽度为0.8,因此这意味着您需要在绘制矩形时传递x0 = 2.6,x1 = 3.4fig.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)

enter image description here


1
老兄,这个完美地运行了;非常感谢你,伙计! - Leonardo Ferreira
不用客气 - 很高兴我的回答对您有帮助! - Derek O

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接