熊猫情节axvspan

时间:2016-11-28 20:34:38

标签: pandas matplotlib visualization

我有一个像这样的数据框

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)

生成

             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

我想绘制它并在2月和3月有一个axvspan。由于我的日期是随机的,我如何选择这2个月并使用axvspan

我的绘图代码很简单

ax=df.plot()

1 个答案:

答案 0 :(得分:1)

这是一个例子。如果日期跨越数年,则必须加以改进。您也可以查看this question的答案,因为原则完全相同。

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