Reputation: 363
I am trying to plot a vertical line using axvline
but ending up with the following error.
Update: the question deviates from posted references because only discreet x-axis tick locations are used (as stated by Trenton McKinney).
Error
TypeError: '<' not supported between instances of 'Timestamp' and 'numpy.float64'
Code
import pandas as pd
df = pd.DataFrame({'A': {0: '2020-01-01 06:00:00',
1: '2020-01-01 18:00:00',
2: '2020-01-02 06:00:00',
3: '2020-01-02 18:00:00',
4: '2020-01-03 06:00:00',
5: '2020-01-03 18:00:00',
6: '2020-01-04 06:00:00',
7: '2020-01-04 18:00:00'},
'B': {0: 5, 1: 5, 2: 6, 3:6, 4:7, 5:7, 6:1, 7:1}})
df['A'] = pd.to_datetime(df['A'])
df= df.set_index('A')
ax = df.plot.bar()
ax.axvline(pd.to_datetime('2020-01-02 18:00:00'), color='grey', zorder=1, linestyle='--', marker="v" )
ax.axvline(pd.to_datetime('2020-01-03 00:00:00'), color='grey', zorder=1, linestyle='--', marker="v" )
Upvotes: 1
Views: 1095
Reputation: 153460
You could build your own barchart with a true datetime x-axis using ax.vlines:
import pandas as pd
from matplotlib.dates import DateFormatter
df = pd.DataFrame({'A': {0: '2020-01-01 06:00:00',
1: '2020-01-01 18:00:00',
2: '2020-01-02 06:00:00',
3: '2020-01-02 18:00:00',
4: '2020-01-03 06:00:00',
5: '2020-01-03 18:00:00',
6: '2020-01-04 06:00:00',
7: '2020-01-04 18:00:00'},
'B': {0: 5, 1: 5, 2: 6, 3:6, 4:7, 5:7, 6:1, 7:1}})
df['A'] = pd.to_datetime(df['A'])
df= df.set_index('A')
fig, ax = plt.subplots()
ax.vlines(df.index, [0]*df.shape[0], df['B'], lw=25)
ax.axvline(pd.Timestamp('2020-01-02 18:00:00'), color='grey', zorder=1, linestyle='--', marker="v" )
ax.axvline(pd.Timestamp('2020-01-03 00:00:00'), color='grey', zorder=1, linestyle='--', marker="v" )
myFmt = DateFormatter("%m/%d/%Y %H:%M:%S")
ax.xaxis.set_major_formatter(myFmt)
ax.set_xticks(df.index)
for label in ax.xaxis.get_ticklabels():
label.set_rotation(90)
ax.set_ylim(0,);
Upvotes: 2