Matplotlib Horizontal and Vertical Lines: axhline, axvline, hlines, vlines

Draw horizontal and vertical lines in Matplotlib with axhline, axvline, hlines, and vlines

Use ax.axvline(x) to draw a vertical line and ax.axhline(y) to draw a horizontal line across a Matplotlib plot. To draw a line that starts and stops at specific data values, use ax.vlines(x, ymin, ymax) or ax.hlines(y, xmin, xmax).

Quick Example

import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(4)
minutes = np.arange(60)
response_ms = 180 + rng.normal(0, 18, size=60)
response_ms[34:] += 70  # latency jumps after a deploy

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(minutes, response_ms, color="#334e68")

ax.axhline(250, color="#d64545", linestyle="--", label="Alert threshold (250 ms)")
ax.axvline(34, color="#2f855a", linestyle=":", linewidth=2, label="Deploy")

ax.set(title="API response time", xlabel="Minute", ylabel="Milliseconds")
ax.legend(loc="upper left")
plt.show()

Line chart of API response time with a dashed red horizontal line at 250 ms and a dotted green vertical line at minute 34, where response time jumps

With the pyplot interface, the calls are plt.axhline(250) and plt.axvline(34). They draw on the current Axes and take the same arguments.

axvline vs vlines (and axhline vs hlines)

Function Draws Start and end are given in Several lines per call
ax.axvline(x, ymin=0, ymax=1) Vertical line Fraction of the Axes height (0 to 1) No
ax.axhline(y, xmin=0, xmax=1) Horizontal line Fraction of the Axes width (0 to 1) No
ax.vlines(x, ymin, ymax) Vertical segments Data coordinates Yes
ax.hlines(y, xmin, xmax) Horizontal segments Data coordinates Yes

Use axvline and axhline for reference lines that should always cross the plot, even after you zoom or change the limits. Use vlines and hlines when the ends of the line mean something in your data.

The keyword names differ too: axvline takes color and linestyle, while vlines takes colors and linestyles.

Draw a Partial Line with ymin and ymax

The ymin and ymax arguments of axvline are fractions of the plot height, not y values. ymax=0.5 stops halfway up whatever the y limits are. The same applies to xmin and xmax in axhline.

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.set_xlim(0, 10)
ax.set_ylim(0, 100)

ax.axvline(2, ymax=0.5, color="#6b46c1", linewidth=3)
ax.text(2.15, 20, "axvline(2, ymax=0.5)\nhalf the plot height")

ax.vlines(6, ymin=30, ymax=80, color="#dd6b20", linewidth=3)
ax.text(6.15, 55, "vlines(6, ymin=30, ymax=80)\nfrom y=30 to y=80")

ax.axhline(90, xmin=0.25, xmax=0.75, color="#2b6cb0", linewidth=3)
ax.text(5, 93, "axhline(90, xmin=0.25, xmax=0.75)", ha="center")
plt.show()

Three partial lines: an axvline reaching half the plot height, a vlines segment from y=30 to y=80, and an axhline covering the middle half of the width

vlines also accepts color=, as above, though colors= is the documented parameter.

Plot Multiple Vertical or Horizontal Lines

axvline accepts one position, so passing it a list raises an error. Either loop over the positions, or pass the list to vlines.

releases = [8, 19, 27, 45]

fig, (left, right) = plt.subplots(1, 2, figsize=(9, 3.8), sharey=True)

for day in releases:
    left.axvline(day, color="#805ad5", linestyle="--")
left.set(title="Loop with axvline", xlim=(0, 50), ylim=(0, 1))

right.vlines(releases, ymin=0, ymax=1, transform=right.get_xaxis_transform(),
             colors="#c05621", linestyles="dashed")
right.set(title="One vlines call", xlim=(0, 50))
plt.show()

Two panels with dashed vertical lines at x equals 8, 19, 27 and 45, drawn with a loop on the left and a single vlines call on the right

transform=ax.get_xaxis_transform() keeps x in data coordinates and reads y as a fraction of the height, so ymin=0, ymax=1 spans the whole plot. For horizontal lines, use ax.get_yaxis_transform() with hlines.

vlines and hlines also take one end point per line, which is handy for lollipop charts and for showing each point's distance from a baseline:

months = np.arange(1, 13)
change = np.array([3, 5, 2, -4, -6, -1, 4, 8, 6, -2, -5, 1])
colors = np.where(change >= 0, "#2f855a", "#c53030")

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.vlines(months, ymin=0, ymax=change, colors=colors, linewidth=3)
ax.scatter(months, change, c=colors, s=60, zorder=3)
ax.axhline(0, color="black", linewidth=1)
ax.set(title="Monthly change in subscribers", xlabel="Month", ylabel="Change (%)")
ax.set_xticks(months)
plt.show()

Lollipop chart of monthly subscriber change, with green stems above zero and red stems below

Change Line Style, Color, and Width

axhline and axvline accept the usual line properties:

  • color: a name ("red"), hex string ("#d64545"), or RGB tuple
  • linestyle (or ls): "-", "--", "-.", ":"
  • linewidth (or lw): width in points
  • alpha: transparency from 0 to 1
  • zorder: drawing order. Pass zorder=0 to put a reference line behind your data.
fig, ax = plt.subplots(figsize=(8, 4))
styles = [
    ("-", 1.5, "#2d3748"),
    ("--", 2, "#c53030"),
    ("-.", 2.5, "#2b6cb0"),
    (":", 3, "#2f855a"),
    ((0, (8, 2, 1, 2, 1, 2)), 2, "#b7791f"),  # custom dash pattern
]
for y, (style, width, color) in enumerate(styles):
    ax.axhline(y, linestyle=style, linewidth=width, color=color)
    ax.text(0.5, y + 0.15, f"linestyle={style!r}, linewidth={width}", ha="center",
            transform=ax.get_yaxis_transform())
ax.set_ylim(-0.5, 4.7)
ax.set_yticks([])
ax.set_xticks([])
plt.show()

Five horizontal lines showing solid, dashed, dash-dot, dotted, and custom dash-dot-dot line styles

Label a Line with Text

A label shows up in ax.legend(). To write the text right next to the line, use ax.text with a blended transform: one coordinate is a data value (the line's position) and the other is a fraction of the Axes, so the text stays put when the data range changes.

rng = np.random.default_rng(11)
scores = rng.normal(72, 9, size=400)
mean = scores.mean()
passing = 60

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.hist(scores, bins=30, color="#bee3f8", edgecolor="white")

for x, text, color in [(passing, "Passing", "#c53030"),
                       (mean, f"Mean {mean:.1f}", "#1a365d")]:
    ax.axvline(x, color=color, linewidth=2)
    # x is a data value, y is a fraction of the Axes height.
    ax.text(x, 0.96, f" {text}", color=color, fontweight="bold", va="top",
            transform=ax.get_xaxis_transform())

ax.set(title="Exam scores", xlabel="Score", ylabel="Students")
plt.show()

Histogram of exam scores with labeled vertical lines for the passing score of 60 and the mean

For a horizontal line, swap it around: ax.text(0.99, y, "Target", ha="right", va="bottom", transform=ax.get_yaxis_transform()). For arrows pointing at a line, see annotations with arrows.

Vertical Lines on a Date Axis

Pass a date to axvline in the same type as your x data, such as datetime, np.datetime64, or a pandas Timestamp. hlines takes dates for xmin and xmax, which lets you draw an average for each period.

dates = np.arange("2026-01-01", "2026-07-01", dtype="datetime64[D]")
rng = np.random.default_rng(8)
visits = 900 + np.arange(len(dates)) * 2 + rng.normal(0, 60, len(dates))

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(dates, visits, color="#a0aec0", linewidth=1)

ax.axvline(np.datetime64("2026-03-15"), color="#c53030", linestyle="--",
           label="Redesign launch")

for start, end in [("2026-01-01", "2026-04-01"), ("2026-04-01", "2026-07-01")]:
    start, end = np.datetime64(start), np.datetime64(end)
    quarter = (dates >= start) & (dates < end)
    ax.hlines(visits[quarter].mean(), start, end, colors="#2b6cb0", linewidth=3)

ax.plot([], [], color="#2b6cb0", linewidth=3, label="Quarterly average")
ax.set(title="Daily visits", ylabel="Visits")
ax.legend()
fig.autofmt_xdate()
plt.show()

Daily visits over six months with a dashed vertical line at the March 15 redesign launch and two horizontal quarterly average lines

To shade a period instead of marking one date, use ax.axvspan(start, end, alpha=0.2). See highlighting a date range.

Add the Same Line to Every Subplot

Loop over the Axes. With sharey=True, one threshold is directly comparable across panels.

rng = np.random.default_rng(2)
fig, axs = plt.subplots(1, 3, figsize=(9, 3.2), sharey=True)

for ax, region, center in zip(axs, ["North", "Central", "South"], [42, 55, 63]):
    ax.bar(range(1, 9), rng.normal(center, 6, 8), color="#9f7aea")
    ax.axhline(50, color="black", linestyle="--", linewidth=1.5)
    ax.set_title(region)

axs[0].set_ylabel("Units sold (target: 50)")
plt.show()

Three bar chart subplots for North, Central and South, each with the same dashed target line at 50

Why is my line missing or changing the axis limits?

  • axhline and axvline expand only their own axis. ax.axvline(500) widens the x limits to include 500 and leaves the y limits alone. If you don't want that, set the axis limits after adding the line.
  • A partial axhline or axvline looks wrong. ymin, ymax, xmin, and xmax must be between 0 and 1. Use vlines or hlines for data values.
  • For a diagonal line, use ax.axline((0, 0), slope=1), or give two points: ax.axline((0, 2), (4, 10)).

Similar Topics