Python 如何在Matplotlib和Pandas中用日期时间绘制阴影区域?

Python 如何在Matplotlib和Pandas中用日期时间绘制阴影区域?,python,pandas,matplotlib,time-series,Python,Pandas,Matplotlib,Time Series,我画了一张图,如下所示 # 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

我画了一张图,如下所示

# 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)
但这似乎不是一个方便或聪明的方法,因为如果有许多阴影区域需要绘制,我必须复制并粘贴许多线条。我怎样才能以明智的方式实现这一点?有没有可能通过循环来实现这一点,我不知道如何循环

使用此数据帧:

    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
使用此数据帧:

    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