Reputation: 3146
I have a dataframe like this
from datetime import date
import random
start_date = date.today().replace(day=1, month=1).toordinal()
end_date = date.today().toordinal()
df=pd.DataFrame.from_dict({'dates':[ date.fromordinal(random.randint(start_date, end_date)) for i in xrange(10) ]
,'n':np.random.randint(0,100,10)})
df.index=df['dates']; del df['dates']
df.sort_index(inplace=True)
Which generates
n
dates
2016-01-24 0
2016-02-26 98
2016-03-04 68
2016-03-26 45
2016-05-03 89
2016-05-09 83
2016-05-11 58
2016-07-29 53
2016-09-18 79
2016-10-20 57
I would like to plot it and have a axvspan for February and March. Since my dates are random how can I select those 2 months and use axvspan
my plotting code is simple
ax=df.plot()
Upvotes: 3
Views: 3515
Reputation: 21878
Here is an example. It has to be improved if the dates span over several years. You can also check the answer to this question since the principle is exactly the same.
ax = df.plot()
# Getting the boundaries for dates in feb and march
period = df[(df.index.month > 1) & (df.index.month < 3)].index
# Highlighting
ax.axvspan(min(period) - MonthBegin(), max(period) + MonthEnd(),
facecolor='g', edgecolor='none', alpha=.2)
Upvotes: 3