使用 matplotlib 的 savefig 保存从 python pandas 生成的图 (AxesSubPlot) [英] Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig
问题描述
我正在使用 Pandas 从数据框中生成一个图,我想将其保存到一个文件中:
I'm using pandas to generate a plot from a dataframe, which I would like to save to a file:
dtf = pd.DataFrame.from_records(d,columns=h)
fig = plt.figure()
ax = dtf2.plot()
ax = fig.add_subplot(ax)
fig.savefig('~/Documents/output.png')
似乎最后一行,使用 matplotlib 的 savefig,应该可以解决问题.但该代码产生以下错误:
It seems like the last line, using matplotlib's savefig, should do the trick. But that code produces the following error:
Traceback (most recent call last):
File "./testgraph.py", line 76, in <module>
ax = fig.add_subplot(ax)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/figure.py", line 890, in add_subplot
assert(a.get_figure() is self)
AssertionError
或者,尝试直接在情节上调用 savefig 也会出错:
Alternatively, trying to call savefig directly on the plot also errors out:
dtf2.plot().savefig('~/Documents/output.png')
File "./testgraph.py", line 79, in <module>
dtf2.plot().savefig('~/Documents/output.png')
AttributeError: 'AxesSubplot' object has no attribute 'savefig'
我想我需要以某种方式将 plot() 返回的子图添加到图形中,以便使用 savefig.我也想知道这是否与 魔法.
I think I need to somehow add the subplot returned by plot() to a figure in order to use savefig. I also wonder if perhaps this has to do with the magic behind the AxesSubPlot class.
以下工作(没有引起错误),但给我留下一个空白页面图像....
the following works (raising no error), but leaves me with a blank page image....
fig = plt.figure()
dtf2.plot()
fig.savefig('output.png')
编辑 2:下面的代码也可以正常工作
EDIT 2: The below code works fine as well
dtf2.plot().get_figure().savefig('output.png')
推荐答案
gcf 方法在 V 0.14 中被弃用,以下代码适用于我:
The gcf method is depricated in V 0.14, The below code works for me:
plot = dtf.plot()
fig = plot.get_figure()
fig.savefig("output.png")
这篇关于使用 matplotlib 的 savefig 保存从 python pandas 生成的图 (AxesSubPlot)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!