Pandas绘制axvspan

3
我有一个像这样的数据框:
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

我想绘制一个图表,并在二月和三月之间使用axvspan。由于我的日期是随机的,我该如何选择这两个月并使用axvspan?
我的绘图代码很简单。
ax=df.plot()

2
axvspan(pd.datetime(2016, 2, 1), pd.datetime(2016,4,1)) 能给你想要的结果吗? - Brian Huey
这个可以。由于某种原因,当我在循环内执行ax.axvspan(pd.datetime(2016,2,1),pd.datetime(2016,4,1))时,我看不到任何东西。否则它正常工作。 - NinjaGaiden
1个回答

3

这里有一个例子。如果日期跨越数年,它需要改进。您还可以查看此问题的答案,因为原理完全相同。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接