使用 matplotlib 的 savefig 保存从 python pandas 生成的图 (AxesSubPlot)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19555525/
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
Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig
提问by bhoward
I'm using pandas to generate a plot from a dataframe, which I would like to save to a file:
我正在使用 Pandas 从数据框中生成一个图,我想将其保存到一个文件中:
dtf = pd.DataFrame.from_records(d,columns=h)
fig = plt.figure()
ax = dtf2.plot()
ax = fig.add_subplot(ax)
fig.savefig('~/Documents/output.png')
It seems like the last line, using matplotlib's savefig, should do the trick. But that code produces the following error:
似乎最后一行,使用 matplotlib 的 savefig,应该可以解决问题。但该代码产生以下错误:
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
Alternatively, trying to call savefig directly on the plot also errors out:
或者,尝试直接在绘图上调用 savefig 也会出错:
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'
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 magicbehind the AxesSubPlot class.
我想我需要以某种方式将 plot() 返回的子图添加到图形中才能使用 savefig。我还想知道这是否与AxesSubPlot 类背后的魔法有关。
EDIT:
编辑:
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
编辑 2:下面的代码也能正常工作
dtf2.plot().get_figure().savefig('output.png')
回答by bhoward
So I'm not entirely sure why this works, but it saves an image with my plot:
所以我不完全确定为什么会这样,但它用我的情节保存了一个图像:
dtf = pd.DataFrame.from_records(d,columns=h)
dtf2.plot()
fig = plt.gcf()
fig.savefig('output.png')
I'm guessing that the last snippet from my original post saved blank because the figure was never getting the axes generated by pandas. With the above code, the figure object is returned from some magic global state by the gcf() call (get current figure), which automagically bakes in axes plotted in the line above.
我猜我原始帖子中的最后一个片段保存为空白,因为该图从未获得熊猫生成的轴。使用上面的代码,图形对象通过 gcf() 调用(获取当前图形)从一些神奇的全局状态返回,它会自动在上图中绘制的轴中烘焙。
回答by Wael Ben Zid El Guebsi
The gcf method is depricated in V 0.14, The below code works for me:
gcf 方法在 V 0.14 中已弃用,以下代码对我有用:
plot = dtf.plot()
fig = plot.get_figure()
fig.savefig("output.png")
回答by Ibelin
It seems easy for me that use plt.savefig()
function after plot()
function:
在plt.savefig()
函数之后使用函数对我来说似乎很容易plot()
:
import matplotlib.pyplot as plt
dtf = pd.DataFrame.from_records(d,columns=h)
dtf.plot()
plt.savefig('~/Documents/output.png')
回答by vamsi chinta
this may be a simpler approach:
这可能是一种更简单的方法:
(DesiredFigure).get_figure().savefig('figure_name.png')
(DesiredFigure).get_figure().savefig('figure_name.png')
i.e.
IE
dfcorr.hist(bins=50).get_figure().savefig('correlation_histogram.png')
回答by joelostblom
You can use ax.figure.savefig()
, as suggested in a comment on the question:
您可以ax.figure.savefig()
按照对问题的评论中的建议使用:
import pandas as pd
df = pd.DataFrame([0, 1])
ax = df.plot.line()
ax.figure.savefig('demo-file.pdf')
This has no practical benefit over ax.get_figure().savefig()
as suggested in other answers, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure()
simply returns self.figure
:
ax.get_figure().savefig()
与其他答案中的建议相比,这没有实际好处,因此您可以选择您认为最美观的选项。事实上,get_figure()
只需返回self.figure
:
# Source from snippet linked above
def get_figure(self):
"""Return the `.Figure` instance the artist belongs to."""
return self.figure