0
0
MatplotlibHow-ToBeginner ยท 3 min read

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:

  • x is the x-position where the vertical line will be drawn.
  • color sets the line color (e.g., 'red', 'blue').
  • linestyle controls the line style (e.g., '-', '--', ':').
  • linewidth sets 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.pyplot as plt.
  • Using plt.vlines() incorrectly, which requires specifying y-limits.
  • Not setting the correct x value, 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

FunctionDescriptionKey Parameters
plt.axvline(x)Draws a vertical line across the entire y-axis at position xcolor, linestyle, linewidth
plt.vlines(x, ymin, ymax)Draws vertical lines from ymin to ymax at x positionsx, ymin, ymax, color, linestyle
plt.axhline(y)Draws a horizontal line across the entire x-axis at position ycolor, 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.