如何在 Pandas 和 Matplotlib 中使用 ax

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29568110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:10:56  来源:igfitidea点击:

How to use ax with Pandas and Matplotlib

pythonnumpypandasmatplotlib

提问by Hound

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.

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

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

Out[122]: enter image description here

出[122]: 在此处输入图片说明

I found this code on stackoverflow to add highlighting.

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

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()

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?

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

回答by Ffisegydd

pandas.DataFrame.plotwill return the matplotlib AxesSubplotobject.

pandas.DataFrame.plot将返回 matplotlibAxesSubplot对象。

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()

If you want to create an axobject in advance, you can pass it into plotas below

如果你想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()

Finally, you can usually get the current figure and axes objects using the following functions

最后,您通常可以使用以下函数获取当前图形和轴对象

fig = plt.gcf()
ax = plt.gca()