HOWTO · Matplotlib

How to Plot Horizontal and Vertical Line in Matplotlib

This tutorial introduces how to plot horizontal and vertical lines in Matplotlib with axhline and axvline, hlines and vlines, and the axhspan and axvspan shading functions.

On this page

To draw horizontal and vertical reference lines in Matplotlib, choose axhline and axvline when the line should span a fraction of the axes, or hlines and vlines when its endpoints should be fixed at data values. When the goal is to highlight a whole band instead of a single value, axhspan and axvspan shade the region between two positions. Each example saves its figure to a temporary PNG file and prints the coordinates of the object it creates, so you can confirm exactly where Matplotlib placed the line or band.

axhline and axvline to Plot Horizontal and Vertical Lines in Matplotlib

axhline to Plot a Horizontal Line

axhline(y=...) places a horizontal line at y in data coordinates. Its xmin and xmax arguments set the left and right ends as fractions of the axes width, normally from 0 to 1; they are not x data values. For example, xmin=0.1 and xmax=0.9 leave a margin equal to 10% of the axes width at each end.

import tempfile
from pathlib import Path

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([0, 2, 4], [1, 3, 2], marker="o")
line = ax.axhline(y=2, xmin=0.1, xmax=0.9, color="tab:red")
ax.set(xlim=(0, 4), ylim=(0, 4), xlabel="x", ylabel="y")
ax.grid(True)
print("x extent (axes fraction):", line.get_xdata())
print("y position (data):", line.get_ydata())
with tempfile.TemporaryDirectory() as directory:
    fig.savefig(Path(directory) / "plot.png")
plt.close(fig)

Output:

x extent (axes fraction): [0.1, 0.9]
y position (data): [2, 2]

The printed values confirm the split: the position is the data value 2, while the extent is stored as the axes fractions 0.1 and 0.9.

Matplotlib plot with a red horizontal line at y = 2 that spans from 10% to 90% of the axes width

The line stays at data value y=2. If you change the x limits, its ends still span 10% to 90% of the axes width, so the segment adjusts to the displayed range.

axvline to Plot a Vertical Line

axvline(x=...) places a vertical line at x in data coordinates. Its ymin and ymax arguments set the bottom and top ends as fractions of the axes height, normally from 0 to 1. For example, ymin=0.1 and ymax=0.9 leave a margin equal to 10% of the axes height at each end.

import tempfile
from pathlib import Path

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([0, 2, 4], [1, 3, 2], marker="o")
line = ax.axvline(x=2, ymin=0.1, ymax=0.9, color="tab:green")
ax.set(xlim=(0, 4), ylim=(0, 4), xlabel="x", ylabel="y")
ax.grid(True)
print("x position (data):", line.get_xdata())
print("y extent (axes fraction):", line.get_ydata())
with tempfile.TemporaryDirectory() as directory:
    fig.savefig(Path(directory) / "plot.png")
plt.close(fig)

Output:

x position (data): [2, 2]
y extent (axes fraction): [0.1, 0.9]

Here the stored values are mirrored: the position is the data value 2, and the extent is the pair of axes fractions.

Matplotlib plot with a green vertical line at x = 2 that spans from 10% to 90% of the axes height

The line stays at data value x=2. If you change the y limits, its ends still span 10% to 90% of the axes height. Thus, each ax*line function combines a position in data coordinates with an extent measured as an axes fraction.

hlines and vlines to Plot Horizontal and Vertical Lines in Matplotlib

Use hlines and vlines when the line position and both endpoints should use data coordinates. For hlines, y gives the height and xmin and xmax give the endpoint x values. For vlines, x gives the position and ymin and ymax give the endpoint y values. Changing the plot limits changes which portions are visible, while the line’s data-coordinate position and endpoints stay fixed. Both functions return a LineCollection and accept the usual styling arguments, so this example also sets dashed and dotted styles and adds a legend through the label argument.

import tempfile
from pathlib import Path

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([0, 2, 4], [1, 3, 2], marker="o")
horizontal = ax.hlines(y=2, xmin=1, xmax=3, color="tab:red", linestyles="--",
                       linewidth=2, label="horizontal segment")
vertical = ax.vlines(x=2, ymin=1, ymax=3, color="tab:green", linestyles=":",
                     linewidth=2, label="vertical segment")
ax.set(xlim=(0, 4), ylim=(0, 4), xlabel="x", ylabel="y")
ax.grid(True)
ax.legend(loc="upper left")
print("horizontal segment endpoints:", horizontal.get_segments()[0].tolist())
print("vertical segment endpoints:", vertical.get_segments()[0].tolist())
with tempfile.TemporaryDirectory() as directory:
    fig.savefig(Path(directory) / "plot.png")
plt.close(fig)

Output:

horizontal segment endpoints: [[1.0, 2.0], [3.0, 2.0]]
vertical segment endpoints: [[2.0, 1.0], [2.0, 3.0]]

The printed endpoints are pure data coordinates: the horizontal segment runs from (1, 2) to (3, 2), and the vertical segment runs from (2, 1) to (2, 3).

Matplotlib plot with a dashed red horizontal segment at y = 2 from x = 1 to x = 3 and a dotted green vertical segment at x = 2 from y = 1 to y = 3, identified by a legend

Because all four endpoints use data coordinates, zooming or changing the limits changes the visible portion of each segment rather than resizing its endpoints to match a fraction of the axes.

axhspan and axvspan to Shade a Region in Matplotlib

When a single line is not enough, shade the region between two values instead. axhspan(ymin, ymax) fills a horizontal band between two y data values across the full width of the axes, and axvspan(xmin, xmax) fills a vertical band between two x data values across the full height. Use them to mark an acceptable range, a target zone or a period of interest behind your data. Both functions return a Rectangle patch.

import tempfile
from pathlib import Path

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([0, 2, 4], [1, 3, 2], marker="o")
band_y = ax.axhspan(ymin=1.5, ymax=2.5, color="tab:orange", alpha=0.3,
                    label="y between 1.5 and 2.5")
band_x = ax.axvspan(xmin=1.5, xmax=2.5, color="tab:blue", alpha=0.15,
                    label="x between 1.5 and 2.5")
ax.set(xlim=(0, 4), ylim=(0, 4), xlabel="x", ylabel="y")
ax.grid(True)
ax.legend(loc="upper left")
print("horizontal band y range:", band_y.get_y(), "to", band_y.get_y() + band_y.get_height())
print("vertical band x range:", band_x.get_x(), "to", band_x.get_x() + band_x.get_width())
with tempfile.TemporaryDirectory() as directory:
    fig.savefig(Path(directory) / "plot.png")
plt.close(fig)

Output:

horizontal band y range: 1.5 to 2.5
vertical band x range: 1.5 to 2.5

Matplotlib plot with an orange horizontal band between y = 1.5 and y = 2.5 and a blue vertical band between x = 1.5 and x = 2.5, identified by a legend

The band edges always use data coordinates. Like axhline, the span functions also accept fraction arguments for the cross direction — axhspan takes xmin and xmax as axes fractions to limit the band’s width, and axvspan takes ymin and ymax — but a band drawn this way still starts and ends at data values.

Why a Horizontal or Vertical Line May Not Appear in Matplotlib

Two checks explain almost every missing-line report. The first is a type error: the fraction arguments of axhline and axvline must be numbers. Passing them as strings — a common accident when the values come from a form, a CSV file or a configuration entry — raises a ValueError before anything is drawn:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([0, 2, 4], [1, 3, 2], marker="o")
ax.axhline(y=2, xmin="0.1", xmax="0.9", color="tab:red")
plt.close(fig)

Output:

ValueError: xmin must be a single scalar value, but got 0.1

Convert the values to numbers first, for example with float(...), and the same call succeeds — the first example in this article is exactly that call with numeric fractions.

The second check is the visible range. A line is created in data coordinates even when its position lies outside the current axis limits, so it exists in the figure but is clipped from view:

import tempfile
from pathlib import Path

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([0, 2, 4], [1, 3, 2], marker="o")
line = ax.axhline(y=20, color="tab:red")
ax.set(xlim=(0, 4), ylim=(0, 4), xlabel="x", ylabel="y")
ax.grid(True)
print("line y position:", line.get_ydata())
print("axes y limits:", tuple(float(v) for v in ax.get_ylim()))
with tempfile.TemporaryDirectory() as directory:
    fig.savefig(Path(directory) / "plot.png")
plt.close(fig)

Output:

line y position: [20, 20]
axes y limits: (0.0, 4.0)

The line sits at y=20 while the axes stop at 4.0. Extend the limits to include the position — or correct the value if 20 was a mistake — and the line appears. The same check applies to hlines and vlines endpoints and to span edges that fall outside the limits.

Conclusion of Drawing Horizontal and Vertical Lines in Matplotlib

Choose axhline or axvline when the position is a data value but the line’s extent should track a fraction of the axes. Choose hlines or vlines when the position and both endpoints should remain at data values, and use axhspan or axvspan when a whole band between two values needs emphasis instead of a single line. This coordinate choice determines how much of a line is visible after you change the plot limits — and comparing the stored coordinates with the axis limits explains any line that seems to be missing.