如何在 Pandas 和 Matplotlib 中使用 ax

How to use ax with Pandas and Matplotlib

我有一个非常基本的问题。我正在使用 pandas 数据框来制作此图,但我想在某些日期周围添加突出显示。

In[122]:
df1_99.plot(x='date', y='units', ylim=[0,11], figsize=[12,12])

输出[122]:

我在 Whosebug 上找到这段代码来添加突出显示。

fig, ax = plt.subplots()
ax.plot_date(t, y, 'b-')
ax.axvspan(*mdates.datestr2num(['10/27/2011', '11/2/2011']), color='red', alpha=0.5)
fig.autofmt_xdate()
plt.show()

我的问题是如何将 ax.avxspan 与我当前的代码一起使用?或者我是否需要将 x='date' 和 y='units' 转换为 numpy 数组并使用上面代码中的格式?

pandas.DataFrame.plot 将 return matplotlib AxesSubplot 对象。

ax = df1_99.plot(x='date', y='units', ylim=[0,11], figsize=[12,12])

ax.axvspan(*mdates.datestr2num(['10/27/2011', '11/2/2011']), color='red', alpha=0.5)
plt.show()

如果你想提前创建一个ax对象,你可以像下面这样传给plot

fig, ax = plt.subplots()

df1_99.plot(x='date', y='units', ylim=[0,11], figsize=[12,12], ax=ax)

ax.axvspan(*mdates.datestr2num(['10/27/2011', '11/2/2011']), color='red', alpha=0.5)
plt.show()

最后,您通常可以使用 the following functions

获取当前图形和轴对象
fig = plt.gcf()
ax = plt.gca()