How to draw vertical lines on a given plot in matplotlib
The standard way to add vertical lines that will cover your entire plot window without you having to specify their actual height is plt.axvline
import matplotlib.pyplot as plt
plt.axvline(x=0.22058956)
plt.axvline(x=0.33088437)
plt.axvline(x=2.20589566)
OR
xcoords = [0.22058956, 0.33088437, 2.20589566]
for xc in xcoords:
plt.axvline(x=xc)
You can use many of the keywords available for other plot commands (e.g. color
, linestyle
, linewidth
...). You can pass in keyword arguments ymin
and ymax
if you like in axes corrdinates (e.g. ymin=0.25
, ymax=0.75
will cover the middle half of the plot). There are corresponding functions for horizontal lines (axhline
) and rectangles (axvspan
).
For multiple lines
xposition = [0.3, 0.4, 0.45]
for xc in xposition:
plt.axvline(x=xc, color='k', linestyle='--')
If someone wants to add a legend
and/or colors
to some vertical lines, then use this:
import matplotlib.pyplot as plt
# x coordinates for the lines
xcoords = [0.1, 0.3, 0.5]
# colors for the lines
colors = ['r','k','b']
for xc,c in zip(xcoords,colors):
plt.axvline(x=xc, label='line at x = {}'.format(xc), c=c)
plt.legend()
plt.show()
Results: