How to set the border of a Bar chart as dash or dots instead of solid?

Hey Fellows,

I’m trying to create a bar chart like the image below:

image



I did create a code that is almost there, but I’m not finding ANY reference about how to set a dashed borderline… Please, could someone help me with this?

My version of the chart is:

image




I set the reproducible code below:

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)

Any help is very welcome!

Regards,
Leonardo

Heey guys, I did receive an answer on my StackOverflow question;

The great solution was provided by the user Derek O

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)
    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_line_width=3
    )])

    fig.update_layout(title_text=None, paper_bgcolor=blank, 
                      height=300, margin={"b":4, "t":4, "l":8, "r":8 })
    
    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)




It will create the expected result:

Regards,
Leonardo

1 Like