0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Add Horizontal Line in Matplotlib: Simple Guide

To add a horizontal line in Matplotlib, use the axhline() function with the y-coordinate where you want the line. For example, plt.axhline(y=0.5) draws a horizontal line at y=0.5 across the plot.
๐Ÿ“

Syntax

The main function to add a horizontal line in Matplotlib is axhline(). It has these key parts:

  • y: The y-coordinate where the line will be drawn.
  • xmin and xmax: The start and end points of the line on the x-axis, as fractions from 0 to 1 (default is full width).
  • color: The color of the line.
  • linestyle: The style of the line (solid, dashed, etc.).
  • linewidth: The thickness of the line.
python
plt.axhline(y=0.5, xmin=0, xmax=1, color='r', linestyle='--', linewidth=2)
๐Ÿ’ป

Example

This example shows how to add a horizontal line at y=0.5 on a simple plot. The line is red, dashed, and thicker for visibility.

python
import matplotlib.pyplot as plt

# Create some data
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]

plt.plot(x, y, label='Data')

# Add horizontal line at y=5
plt.axhline(y=5, color='red', linestyle='--', linewidth=2, label='Horizontal line at y=5')

plt.legend()
plt.show()
Output
A line plot with points (0,0), (1,1), (2,4), (3,9), (4,16) and a red dashed horizontal line crossing the y-axis at 5 across the whole plot width.
โš ๏ธ

Common Pitfalls

Some common mistakes when adding horizontal lines in Matplotlib include:

  • Using plt.hlines() incorrectly by confusing data coordinates with axis fractions.
  • Not setting xmin and xmax properly, which can cause the line to not span the expected width.
  • Forgetting to call plt.show() to display the plot.

Here is a wrong and right way example:

python
# Wrong: xmin and xmax are data values, but they should be fractions between 0 and 1
plt.axhline(y=2, xmin=0, xmax=4, color='blue')  # This will not work as expected

# Right: xmin and xmax as fractions
plt.axhline(y=2, xmin=0, xmax=1, color='blue')  # Correct usage
๐Ÿ“Š

Quick Reference

ParameterDescriptionDefault
yY-coordinate for the horizontal lineRequired
xminStart of line on x-axis (fraction 0 to 1)0
xmaxEnd of line on x-axis (fraction 0 to 1)1
colorColor of the line'k' (black)
linestyleStyle of the line (e.g., '-', '--')'-'
linewidthThickness of the line1.0
โœ…

Key Takeaways

Use plt.axhline(y=value) to add a horizontal line at the y position.
xmin and xmax control the horizontal span as fractions of the x-axis width.
Customize color, linestyle, and linewidth to make the line clear.
Always call plt.show() to display your plot with the horizontal line.
Avoid using data coordinates for xmin and xmax; use fractions between 0 and 1.