使用matplotlib的savefig保存从python pandas 生成的图(AxesSubPlot) [英] Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig
问题描述
我正在使用熊猫从数据框生成图,我想将其保存到文件中:
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')
下面的代码也可以正常工作
EDIT 2: The below code works fine as well
dtf2.plot().get_figure().savefig('output.png')
推荐答案
在v 0.14中使用了gcf方法,以下代码对我有用:
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屋!