Plotly: How to add vertical line to plotly plot?

Viewed 11408

I am testing plotly express.

I have the latest version: 0.4.1

I am trying to plot the most basic chart in their tutorial but it's throwing an error:

import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="petal_length", y="petal_width")
fig.add_vline(x=2.5, line_width=3, line_dash="dash", line_color="green")
fig.add_hrect(y0=0.9, y1=2.6, line_width=0, fillcolor="red", opacity=0.2)
fig.show()


AttributeError: 'Figure' object has no attribute 'add_vline'

Am I doing something wrong?

All I want to do is to get add_vline working.

It's the second example on the how-to guide here: https://plotly.com/python/horizontal-vertical-shapes/

2 Answers

As of plotly version 4.12, which you seem to not be running, you can add Horizontal and Vertical Lines and Rectangles. So for your case, just use:

fig.add_vline()

And there's nothing wrong with your code on my end. This exact snippet:

import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="petal_length", y="petal_width")
fig.add_vline(x=2.5, line_width=3, line_dash="dash", line_color="green")
fig.add_hrect(y0=0.9, y1=2.6, line_width=0, fillcolor="red", opacity=0.2)
fig.show()

...produces this figure:

enter image description here

Which plotly version are you running?

To run the minimal example your package plotly has to be up to date as well as your package plotly.express.

import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="petal_length", y="petal_width")
fig.add_hline(y=0.9)
fig.add_vrect(x0=0.9, x1=2)
fig.show()

I quote from the documentation you have shared.

add_hline, add_vline, add_hrect, and add_vrect is introduced in plotly 4.12.

Please bring your package on this or a newer version.

Related