Explain Codes LogoExplain Codes Logo

How to draw vertical lines on a given plot

python
plot-engineering
data-visualization
matplotlib
Nikita BarsukovbyNikita Barsukov·Nov 27, 2024
TLDR

Swiftly add a vertical line to a plot in matplotlib using axvline. It's really this straightforward:

import matplotlib.pyplot as plt # Your data x = range(10) y = [i**2 for i in x] plt.plot(x, y) # All things being equal, y would be a perfect square! plt.axvline(x=5, color='r', linestyle='--') # Get in line, x=5! You're up next! plt.show() # Show off your masterpiece

Key points: exploit plt.axvline(x, color, linestyle) to draw. Modify the x-coordinate, color, and linestyle to cater to your unique taste.

Broadening vertical lines scope

Vertical lines are more than pretty doodles on your plot. They conveniently highlight occurrence, data thresholds, or boundaries.

Drawing the battalion of lines

You can summon multiple vertical lines in one stroke using a loop, especially handy when pointing out a series of keypoints on a plot:

key_x = [3, 6, 9] # Rendezvous points for x_spot in key_x: plt.axvline(x=x_spot, color='blue', linestyle=':', linewidth=2) # Line-up, soldiers!

Mini-me of lines

At times, a full-length line may overpower or muddle your plot. Put them on a diet with ymin and ymax options, scaled between 0 and 1:

plt.axvline(x=5, color='green', linestyle='-.', ymin=0.25, ymax=0.75) # Diet starts today, line at x=5!

Group attendees with lines

axvspan to the rescue for group photoshoots between two x-coordinates, ideal for underlining particular periods:

plt.axvspan(xmin=4.5, xmax=6.5, facecolor='grey', alpha=0.5) # Group photo between x=4.5 and x=6.5! Smile!

Precision with vlines

For the fans of precision, the vlines function plots multiple lines in one go with individual settings for each:

plt.vlines(x=[1, 2, 3], ymin=[2, 4, 6], ymax=[8, 10, 12], colors=['red', 'blue', 'green'], linestyles='solid') # Red, blue, and green lines walk into a bar...

Horizontal buddies of vertical lines

We've been talking about vertical lines, but their horizontal siblings (axhline and axhspan) interested in meeting you! They can highlight specific ranges on the y-axis.

Skipping the scaling tantrums

scaley=False is the trick to stop automatic adjustment of y-limits when you're playing with axhline or vlines. Keep your lines true to their datapoints.

Potential stumbling blocks

As you traverse along this path, look out for some hurdles:

  • Your lines may not appear if they're out of axis bounds. Do a reality check with your axis range.
  • Lines may play hide-and-seek behind other plot elements. Resolve the game by setting the zorder.
  • Excessive lines could result in visual congestion, impeding interpretation. Keep it minimal on transparency and leverage interactive tools.