Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas plot axvspan

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()
like image 214
NinjaGaiden Avatar asked Sep 16 '26 14:09

NinjaGaiden


1 Answers

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)

enter image description here

like image 71
Romain Avatar answered Sep 21 '26 15:09

Romain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!