Pandas 情节 axvspan

标签 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

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

我的绘图代码很简单

ax=df.plot()

最佳答案

这是一个例子。如果日期跨越数年,则必须对其进行改进。您还可以查看 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

关于 Pandas 情节 axvspan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40852958/

相关文章:

matplotlib - 如何使用 matplotlib 在两条直方图线之间完成颜色填充?

python - 删除matplotlib python中散点图的轮廓颜色

javascript - Material 谷歌折线图中的对数刻度

python - Mac OS X 和 TeX Live 上 matplotlib 中的 TeX

python - Pandas 根据 df1 中表示 df2 间隔的列检索值

python - Pandas 。转换表结构

python - Pandas:设置滑动窗口以迭代行并应用函数

python - 仅具有高亮值的 matplotlib 条形图

d3.js - 在 G 元素中选择路径并更改样式

python - 根据对象的类型(即 str)从 DataFrame 中选择行