The plotly equivalent of matplotlib "vlines"

matplotlib has a function “vlines” that allows for adding multiple vertical lines with adjustable lengths (y0,y1).
It seems the add_vline function in plotly is the closest function but, 1) it plots the vertical line extending across the entire y-axis range, and 2) it doesn’t plot multiple vertical lines. Does plotly have a function that produces the same output as the matplotlib “vlines” function?

Hi @nourma2 ,

I don’t think that there is such a builtin function. You could create a scatterplot with the y0,y1, mode=‘lines’ and this as trace to your figure.

You could also create lines as annotations.

EDIT: I created a function for testing purposes (quick an dirty)

import plotly.graph_objects as go

def add_lines(orientation, levels, bounds):
    if orientation == 'h':
        traces = [
            go.Scatter(x=bounds, y=[level]*2, mode='lines', name=f'{orientation}_line_{idx}')
            for idx, level in enumerate(levels)
        ]
    else:
        traces = [
            go.Scatter(x=[level]*2, y=bounds, mode='lines', name=f'{orientation}_line_{idx}')
            for idx, level in enumerate(levels)
        ]
    return traces

# example usage:

# create base figure
fig = go.Figure(data=go.Scatter(x=[1,2,3], y=[1,2,3]))

# add lines
fig.add_traces(
    add_lines(
        orientation='v', 
        levels=[1.5, 2, 2.5], 
        bounds=[1.5, 2.5]
    )
)
1 Like

Makes sense. Thank you for your help!