Adding Vertical Lines in Plotly

Vertical lines (vlines) are a great way to highlight specific x-values on a Plotly chart—whether it’s a threshold, a special event, or a point of interest. Learn how to use Plotly to create vertical lines in both Plotly Express and Graph Objects.

Using Plotly Express with Shapes

Plotly Express doesn’t have a direct vline function, but you can add vertical lines using the update_layout method and shapes:

import plotly.express as px

# Sample data
df = px.data.iris()

# Base scatter plot
fig = px.scatter(df, x="sepal_width", y="sepal_length")

# Add vertical line at x = 3.5
fig.update_layout(
    shapes=[dict(
        type="line",
        x0=3.5, x1=3.5,
        y0=0, y1=8,
        line=dict(color="Red", width=2, dash="dash")
    )]
)

fig.show()

This example adds a red dashed vertical line at x = 3.5 spanning from y = 0 to y = 8.

Using Plotly Graph Objects

If you’re using plotly.graph_objects, the method is similar but gives more control:

import plotly.graph_objects as go

fig = go.Figure()

# Add scatter trace
fig.add_trace(go.Scatter(x=[1, 2, 3, 4], y=[10, 11, 12, 13], mode='lines+markers'))

# Add vertical line at x = 2.5
fig.add_shape(
    type="line",
    x0=2.5, x1=2.5,
    y0=0, y1=15,
    line=dict(color="Green", width=2)
)

fig.show()

Multiple Vertical Lines

You can easily add multiple vlines by including more entries in the shapes list:

fig.update_layout(
    shapes=[
        dict(type="line", x0=2, x1=2, y0=0, y1=15, line=dict(color="blue")),
        dict(type="line", x0=3, x1=3, y0=0, y1=15, line=dict(color="orange", dash="dot"))
    ]
)
See also  Creating Interactive Scatter Plots with Plotly in Python