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.xminandxmax: 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
xminandxmaxproperly, 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
| Parameter | Description | Default |
|---|---|---|
| y | Y-coordinate for the horizontal line | Required |
| xmin | Start of line on x-axis (fraction 0 to 1) | 0 |
| xmax | End of line on x-axis (fraction 0 to 1) | 1 |
| color | Color of the line | 'k' (black) |
| linestyle | Style of the line (e.g., '-', '--') | '-' |
| linewidth | Thickness of the line | 1.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.