How to Add Vertical Line in Matplotlib: Simple Guide
To add a vertical line in Matplotlib, use the
plt.axvline(x) function where x is the x-coordinate of the line. You can customize the line style, color, and width by adding parameters like color, linestyle, and linewidth.Syntax
The basic syntax to add a vertical line in Matplotlib is:
plt.axvline(x, color='color', linestyle='style', linewidth=width)
Here:
xis the x-position where the vertical line will be drawn.colorsets the line color (e.g., 'red', 'blue').linestylecontrols the line style (e.g., '-', '--', ':').linewidthsets the thickness of the line.
python
plt.axvline(x=2, color='green', linestyle='--', linewidth=2)
Example
This example shows how to plot a simple line chart and add a vertical dashed red line at x=3.
python
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] plt.plot(x, y, label='Data') plt.axvline(x=3, color='red', linestyle='--', linewidth=2, label='Vertical Line at x=3') plt.legend() plt.title('Plot with Vertical Line') plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.show()
Output
A line plot with points (1,2), (2,3), (3,5), (4,7), (5,11) and a vertical dashed red line crossing the x-axis at 3.
Common Pitfalls
Common mistakes when adding vertical lines include:
- Forgetting to import
matplotlib.pyplotasplt. - Using
plt.vlines()incorrectly, which requires specifying y-limits. - Not setting the correct
xvalue, causing the line to appear outside the plot range. - Overlapping lines without labels, making the plot confusing.
python
import matplotlib.pyplot as plt # Correct: Using plt.vlines with y-limits plt.plot([1, 2, 3], [4, 5, 6]) plt.vlines(x=2, ymin=0, ymax=7, color='blue') # Correct usage # Right: Using plt.axvline for a full vertical line plt.axvline(x=2, color='red', linestyle='--') plt.show()
Output
A plot with a blue vertical line from y=0 to y=7 at x=2 and a red dashed vertical line crossing entire y-axis at x=2.
Quick Reference
| Function | Description | Key Parameters |
|---|---|---|
| plt.axvline(x) | Draws a vertical line across the entire y-axis at position x | color, linestyle, linewidth |
| plt.vlines(x, ymin, ymax) | Draws vertical lines from ymin to ymax at x positions | x, ymin, ymax, color, linestyle |
| plt.axhline(y) | Draws a horizontal line across the entire x-axis at position y | color, linestyle, linewidth |
Key Takeaways
Use plt.axvline(x) to add a vertical line at position x easily.
Customize the line with color, linestyle, and linewidth parameters.
Ensure the x value is within the plot range to see the line.
plt.vlines requires ymin and ymax to define line length explicitly.
Always label lines when plotting multiple elements for clarity.