I want to draw line markers on a bar plot

I have a horizontal bar plot and want to draw a vertical line over each one. I’m using shapes property to do this and i’m the following situation: i have the x0 and x1 of the line but, i need the bar width to specify the start and end y points for this line because the y axis variable is categorical. How can i draw it?

@yuricda96 To plot a vertical line over the horizonthal bars, you can perform the following trick:

define a subplot with 1 row and 1 column with two yaxes (one at the left side and another at the right one, but invisible). The bars are referenced with respect to xaxis and yaxis (categorical , at left side), while the vertical line with respect to the same xaxis and yaxis2 (i.e. the right side y-axis):

import plotly.graph_objects as go
from plotly.subplots import make_subplots

bars = go.Bar(y= ['A', 'B', 'C', "D"], x =[12, 8, 15, 10],  orientation='h')

line = go.Scatter(y= [0, 1],
                  x= [7, 7],
                  mode= 'lines',
                  showlegend= False,

fig = make_subplots(specs=[[{"secondary_y": True}]], print_grid=True)
fig.add_trace(bars, 1, 1, secondary_y=False)
fig.add_trace(line, 1, 1, secondary_y=True)
fig.update_layout(width=600, height=400, yaxis2= dict(fixedrange= True,
                                                      range= [0, 1],
                                                      visible= False))


If you want to be displayed on hover the y-value along the vertical line, then remove hoverinfo='none',
and eventually add more elements in x and y lists in the line definition.

See here more examples on multiple axes https://plot.ly/python/multiple-axes/.

Thanks @empet, that’s what i need!

1 Like