如何在 Pandas 和 Matplotlib 中使用 ax [英] How to use ax with Pandas and Matplotlib
问题描述
我有一个非常基本的问题.我正在使用pandas数据框进行绘制,但是我想在某些日期周围添加突出显示.
I have a very basic question. I am using a pandas dataframe to make this plot, but I want to add highlighting around certain dates.
In[122]:
df1_99.plot(x='date', y='units', ylim=[0,11], figsize=[12,12])
出[122]:
我在 stackoverflow 上找到了这段代码来添加突出显示.
I found this code on stackoverflow to add highlighting.
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 数组并使用上面代码中的格式?
My question is how can I use ax.avxspan with my current code? Or do I need to convert my x='date', and y='units' to numpy arrays and use the format as in the code above?
推荐答案
pandas.DataFrame.plot
将返回 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
中.
If you want to create an ax
object in advance, you can pass it into plot
as below
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()
最后,您通常可以使用以下函数获取当前图形和轴对象
fig = plt.gcf()
ax = plt.gca()
这篇关于如何在 Pandas 和 Matplotlib 中使用 ax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!