matplotlib 如何使用日期时间绘制阴影区域

knpiaxh1  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(169)

我画了一个如下的图

# Retrieve data from FRED, check my notebook for pandareader's user guide
start = dt.datetime(1951, 1, 1)
end = dt.datetime.today()
V_M1 = pdr.data.DataReader('M1V', 'fred', start, end)
V_M2 = pdr.data.DataReader('M2V', 'fred', start, end)

fig, ax = plt.subplots(figsize = (13, 8))
ax.plot(V_M1, color = 'CornflowerBlue', alpha = 1, label = 'Velocity of M1 Stock', lw = 2)
ax.set_ylabel('M1 Velocity', size = 14, color = 'CornflowerBlue')

ax_RHS = ax.twinx() # share the same x-axis
ax_RHS.plot(V_M2, color = 'DarkGoldenRod', alpha = .7, label = 'Velocity of M2 Stock', lw = 2)
ax_RHS.set_ylabel('M2 Velocity', size = 14, color = 'DarkGoldenRod')

ax.legend(fontsize = 13, loc = 'lower left')
ax_RHS.legend(fontsize = 13, loc = 'upper right')
ax.yaxis.grid(True) # only horizontal grid
ax.set_title('US Monetary Velocity', size = 16)

plt.show()

我得到了一个只有日期的数据集

Peak, Trough
1960-04-01, 1961-02-01
1969-12-01, 1970-11-01
1973-11-01, 1975-03-01
1980-01-01, 1980-07-01
1981-07-01, 1982-11-01
1990-07-01, 1991-03-01
2001-03-01, 2001-11-01
2007-12-01, 2009-06-01

如何在这些日期之间绘制阴影区域?例如,在“2007-12-01”和“2007-12- 01”之间,我想在绘图中添加阴影区域?
例如,我可以使用

ax.axvspan('2007-12-1','2009-6-1',color = 'gray', alpha = .5, zorder = -1)

但这似乎不是一个方便或聪明的方式,因为我必须复制和粘贴许多行,如果有许多阴影区绘制。我如何才能实现这一点在一个聪明的方式?是否有可能实现这一点通过一个循环,我不知道如何循环。

ktecyv1j

ktecyv1j1#

使用此 Dataframe :

Peak    Trough
0   1960-04-01  1961-02-01
1   1969-12-01  1970-11-01
2   1973-11-01  1975-03-01
3   1980-01-01  1980-07-01
4   1981-07-01  1982-11-01
5   1990-07-01  1991-03-01
6   2001-03-01  2001-11-01
7   2007-12-01  2009-06-01

转换为日期时间:

for col in df.columns:
    df[col] = pd.to_datetime(df[col])

然后迭代 Dataframe 并绘制阴影区域:

for ix, row in df.iterrows():
    plt.fill_between(row, 3, color='blue', alpha=.5)
#                         ^ determines the height

相关问题