Horizontal and Vertical Lines and Rectangles in Python

How to add annotated horizontal and vertical lines in Python.


New to Plotly?

Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Horizontal and Vertical Lines and Rectangles

introduced in plotly 4.12

Horizontal and vertical lines and rectangles that span an entire plot can be added via the add_hline, add_vline, add_hrect, and add_vrect methods of plotly.graph_objects.Figure. Shapes added with these methods are added as layout shapes (as shown when doing print(fig), for example). These shapes are fixed to the endpoints of one axis, regardless of the range of the plot, and fixed to data coordinates on the other axis. The following shows some possibilities, try panning and zooming the resulting figure to see how the shapes stick to some axes:

In [1]:
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()

These shapes can be styled by passing the same arguments as are accepted by add_shape:

In [2]:
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()

Horizontal and vertical lines in Dash

Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run pip install dash, click "Download" to get the code and run python app.py.

Get started with the official Dash docs and learn how to effortlessly style & deploy apps like this with Dash Enterprise.

Out[3]:

Sign up for Dash Club → Free cheat sheets plus updates from Chris Parmer and Adam Schroeder delivered to your inbox every two months. Includes tips and tricks, community apps, and deep dives into the Dash architecture. Join now.

Adding Text Annotations

Text annotations can optionally be added to an autoshape using the annotation_text keyword argument, and positioned using the annotation_position argument:

In [4]:
import plotly.express as px

df = px.data.stocks(indexed=True)
fig = px.line(df)
fig.add_hline(y=1, line_dash="dot",
              annotation_text="Jan 1, 2018 baseline", 
              annotation_position="bottom right")
fig.add_vrect(x0="2018-09-24", x1="2018-12-18", 
              annotation_text="decline", annotation_position="top left",
              fillcolor="green", opacity=0.25, line_width=0)
fig.show()

Extra formatting of the annotation can be done using magic-underscores prefixed by annotation_ or by passing a dict or go.layout.Annotation instance to the annotation argument:

In [5]:
import plotly.express as px

df = px.data.stocks(indexed=True)
fig = px.line(df)
fig.add_hline(y=1, line_dash="dot",
              annotation_text="Jan 1, 2018 baseline", 
              annotation_position="bottom right",
              annotation_font_size=20,
              annotation_font_color="blue"
             )
fig.add_vrect(x0="2018-09-24", x1="2018-12-18", 
              annotation_text="decline", annotation_position="top left",
              annotation=dict(font_size=20, font_family="Times New Roman"),
              fillcolor="green", opacity=0.25, line_width=0)
fig.show()

Adding to Multiple Facets / Subplots

The same line or box can be added to multiple subplots or facets by setting the row and/or col to "all". The default row and col values are "all".

In [6]:
import plotly.express as px

df = px.data.stocks(indexed=True)
fig = px.line(df, facet_col="company", facet_col_wrap=2)
fig.add_hline(y=1, line_dash="dot", row=3, col="all",
              annotation_text="Jan 1, 2018 baseline", 
              annotation_position="bottom right")
fig.add_vrect(x0="2018-09-24", x1="2018-12-18", row="all", col=1,
              annotation_text="decline", annotation_position="top left",
              fillcolor="green", opacity=0.25, line_width=0)
fig.show()

Text Labels on Shapes

New in 5.14

Text labels on shapes, introduced in version 5.14, is now the recommended way to add text to shapes. The above examples using add_hline, add_vrect, add_hrect, and add_vline that add annotations can be rewritten to use label.

In [7]:
import plotly.express as px

df = px.data.stocks(indexed=True)
fig = px.line(df)
fig.add_hline(
    y=1,
    line_dash="dot",
    label=dict(
        text="Jan 1 2018 Baseline",
        textposition="end",
        font=dict(size=20, color="blue"),
        yanchor="top",
    ),
)
fig.add_vrect(
    x0="2018-09-24",
    x1="2018-12-18",
    label=dict(
        text="Decline",
        textposition="top center",
        font=dict(size=20, family="Times New Roman"),
    ),
    fillcolor="green",
    opacity=0.25,
    line_width=0,
)
fig.show()

With text labels on shapes, you can also add text labels to shapes other than lines and rectangles, and the labels can be added automatically to shapes drawn by the user.

Reference

More details are available about layout shapes and annotations.

Reference documentation is also available for add_hline, add_vline, add_hrect, add_vrect.

What About Dash?

Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash at https://dash.plot.ly/installation.

Everywhere in this page that you see fig.show(), you can display the same figure in a Dash application by passing it to the figure argument of the Graph component from the built-in dash_core_components package like this:

import plotly.graph_objects as go # or plotly.express as px
fig = go.Figure() # or any Plotly Express function e.g. px.bar(...)
# fig.add_trace( ... )
# fig.update_layout( ... )

from dash import Dash, dcc, html

app = Dash()
app.layout = html.Div([
    dcc.Graph(figure=fig)
])

app.run_server(debug=True, use_reloader=False)  # Turn off reloader if inside Jupyter