86
  • How do you plot a vertical line (vlines) in a Pandas series plot?
  • I am using Pandas to plot rolling means, etc., and would like to mark important positions with a vertical line.
  • Is it possible to use vlines, or something similar, to accomplish this?
  • In this case, the x axis is datetime.
Trenton McKinney
  • 43,885
  • 25
  • 111
  • 113
aetodd
  • 971
  • 1
  • 8
  • 6

4 Answers4

118
plt.axvline(x_position)

It takes the standard plot formatting options (linestlye, color, ect)

(doc)

If you have a reference to your axes object:

ax.axvline(x, color='k', linestyle='--')
tacaswell
  • 79,602
  • 19
  • 200
  • 189
  • 3
    Yes, you have access to the axes object ax = s.plot(), where s is a pandas.Series – joao Mar 29 '16 at 16:55
48

If you have a time-axis, and you have Pandas imported as pd, you can use:

ax.axvline(pd.to_datetime('2015-11-01'), color='r', linestyle='--', lw=2)

For multiple lines:

xposition = [pd.to_datetime('2010-01-01'), pd.to_datetime('2015-12-31')]
for xc in xposition:
    ax.axvline(x=xc, color='k', linestyle='-')
Eric Leschinski
  • 135,913
  • 89
  • 401
  • 325
zbinsd
  • 3,824
  • 6
  • 32
  • 38
  • I have a 3-day plot and all I did was: `xposition = [pd.to_datetime('01/04/2016'), pd.to_datetime('02/04/2016'),pd.to_datetime('03/04/2016')]` then `for xc in xposition: ax.axvline(x=xc, color='k', linestyle='-')`. And I got: `ValueError: ordinal must be >= 1.`. What's wrong? – FaCoffee Apr 27 '18 at 09:21
  • @FaCoffee, your dates are in a different format from the example given in the answer, though I can't see how that would make a difference. – RufusVS Oct 10 '18 at 15:50
  • I'd like to plot a vertical line on a time series column plot for each day, any help please ? – Ikbel Feb 26 '19 at 10:44
  • how can I put a label to this line? Or how to put this line to the legend? – Maxl Gemeinderat Feb 17 '22 at 14:04
15

DataFrame plot function returns AxesSubplot object and on it, you can add as many lines as you want. Take a look at the code sample below:

%matplotlib inline

import pandas as pd
import numpy as np

df = pd.DataFrame(index=pd.date_range("2019-07-01", "2019-07-31"))  # for sample data only
df["y"] = np.logspace(0, 1, num=len(df))  # for sample data only

ax = df.plot()
# you can add here as many lines as you want
ax.axhline(6, color="red", linestyle="--")
ax.axvline("2019-07-24", color="red", linestyle="--")

enter image description here

Trenton McKinney
  • 43,885
  • 25
  • 111
  • 113
Roman Orac
  • 1,294
  • 14
  • 18
5

matplotlib.pyplot.vlines

  • For a time series, the dates for the axis must be proper datetime objects, not strings.
  • Allows for single or multiple locations
  • ymin & ymax are specified as a specific y-value, not as a percent of ylim
  • If referencing axes with something like fig, axes = plt.subplots(), then change plt.xlines to axes.xlines

plt.plot() & sns.lineplot()

from datetime import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns  # if using seaborn

plt.style.use('seaborn')  # these plots use this style

# configure synthetic dataframe
df = pd.DataFrame(index=pd.bdate_range(datetime(2020, 6, 8), freq='1d', periods=500).tolist())
df['v'] = np.logspace(0, 1, num=len(df))

# plot
plt.plot('v', data=df, color='magenta')

y_min = df.v.min()
y_max = df.v.max()

plt.vlines(x=['2020-07-14', '2021-07-14'], ymin=y_min, ymax=y_max, colors='purple', ls='--', lw=2, label='vline_multiple')
plt.vlines(x=datetime(2021, 9, 14), ymin=4, ymax=9, colors='green', ls=':', lw=2, label='vline_single')
plt.legend(bbox_to_anchor=(1.04, 0.5), loc="center left")
plt.show()

enter image description here

df.plot()

df.plot(color='magenta')

ticks, _ = plt.xticks()
print(f'Date format is pandas api format: {ticks}')

y_min = df.v.min()
y_max = df.v.max()

plt.vlines(x=['2020-07-14', '2021-07-14'], ymin=y_min, ymax=y_max, colors='purple', ls='--', lw=2, label='vline_multiple')
plt.vlines(x='2020-12-25', ymin=y_min, ymax=8, colors='green', ls=':', lw=2, label='vline_single')
plt.legend(bbox_to_anchor=(1.04, 0.5), loc="center left")
plt.show()

enter image description here

package versions

import matplotlib as mpl

print(mpl.__version__)
print(sns.__version__)
print(pd.__version__)

[out]:
3.3.1
0.10.1
1.1.0

Trenton McKinney
  • 43,885
  • 25
  • 111
  • 113