horizontal line
data visualization
plotting
graph customization
matplotlib

Plot a horizontal line on a given plot

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

A horizontal line on a chart is usually a reference value such as a threshold, average, target, or control limit. In Matplotlib, the right tool depends on whether the line should span the entire axes or only a specific x-range, with axhline covering the first case and hlines covering the second.

Use axhline for a Full-Width Reference Line

If the line should run across the whole plotting area at a fixed y-value, use axhline.

python
1import matplotlib.pyplot as plt
2
3x = [1, 2, 3, 4, 5]
4y = [3, 5, 4, 6, 7]
5
6fig, ax = plt.subplots()
7ax.plot(x, y, marker="o", label="series")
8ax.axhline(y=5, color="red", linestyle="--", linewidth=2, label="threshold")
9
10ax.legend()
11plt.show()

This is the usual answer for a baseline or target that applies to the whole chart. It is clearer than drawing a manual two-point line with plot because the intent is obvious from the API.

Use hlines for a Partial Span

If the horizontal line should cover only part of the x-axis, use hlines instead.

python
1import matplotlib.pyplot as plt
2
3fig, ax = plt.subplots()
4ax.plot([0, 1, 2, 3], [1, 4, 2, 5], marker="o")
5ax.hlines(y=3, xmin=1, xmax=2.5, colors="green", linestyles="dotted", linewidth=2)
6
7plt.show()

That is useful when the reference applies only to a subsection of the plot, such as a maintenance window, a highlighted interval, or a band of interest.

Add Meaning With Labels and Annotations

A horizontal line is more useful when the viewer knows what it represents. Add a legend label or annotate the line directly.

python
1import matplotlib.pyplot as plt
2
3values = [10, 12, 9, 14, 11]
4
5fig, ax = plt.subplots()
6ax.plot(values, marker="o")
7ax.axhline(y=11, color="orange", linestyle="--", label="target")
8ax.text(0.1, 11.2, "target = 11", color="orange")
9ax.legend()
10
11plt.show()

This matters because an unlabeled line often forces the reader to guess whether it is an average, an SLA threshold, or just another data series.

Plot a Computed Reference Line

Often the y-value is derived from the data instead of being hard-coded. A mean or median line is a common example.

python
1import matplotlib.pyplot as plt
2import numpy as np
3
4values = np.array([2, 5, 4, 7, 6, 8])
5mean_value = values.mean()
6
7fig, ax = plt.subplots()
8ax.plot(values, marker="o")
9ax.axhline(y=mean_value, color="purple", linestyle="--", label=f"mean = {mean_value:.2f}")
10ax.legend()
11
12plt.show()

This is a simple but effective way to show whether points cluster above or below a computed baseline.

Use the Axes Object in Multi-Plot Figures

When your figure contains subplots, attach the line to the correct axes object rather than relying on the implicit current axes.

python
1import matplotlib.pyplot as plt
2
3fig, axes = plt.subplots(1, 2, figsize=(10, 4))
4
5axes[0].plot([1, 3, 2])
6axes[0].axhline(y=2, color="red")
7
8axes[1].plot([4, 1, 5])
9axes[1].axhline(y=3, color="blue")
10
11plt.tight_layout()
12plt.show()

This avoids drawing the line on the wrong subplot, which is a common mistake in larger notebooks and scripts.

Common Pitfalls

The most common pitfall is using a regular plot call to fake a horizontal reference line when axhline or hlines would express the intent more clearly.

Another issue is forgetting that axhline spans the full axes width, not a limited x-range. If the line should stop early, hlines is the right tool.

Developers also often forget to label the line, which leaves the reader to infer its meaning from context. If the line matters enough to add, it usually matters enough to annotate.

Finally, in figures with several axes, make sure you are calling the method on the intended axes object rather than whichever subplot happens to be current.

Summary

  • Use axhline for a horizontal line that spans the whole axes.
  • Use hlines when the line should cover only part of the x-range.
  • Label or annotate the line so its meaning is obvious.
  • Compute the y-value dynamically when the reference line represents a statistic.
  • Prefer the explicit axes API when working with subplots.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.