Python 将 pandas.Series 直方图保存到文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18992086/
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
save a pandas.Series histogram plot to file
提问by GeauxEric
In ipython Notebook, first create a pandas Series object, then by calling the instance method .hist(), the browser displays the figure.
在ipython Notebook中,首先创建一个pandas Series对象,然后通过调用实例方法.hist(),浏览器显示图形。
I am wondering how to save this figure to a file (I mean not by right click and save as, but the commands needed in the script).
我想知道如何将此图保存到文件中(我的意思不是右键单击并另存为,而是脚本中所需的命令)。
采纳答案by Phillip Cloud
Use the Figure.savefig()
method, like so:
使用该Figure.savefig()
方法,如下所示:
ax = s.hist() # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')
It doesn't have to end in pdf
, there are many options. Check out the documentation.
它不必以 结尾pdf
,有很多选择。查看文档。
Alternatively, you can use the pyplot
interface and just call the savefig
as a function to save the most recently created figure:
或者,您可以使用该pyplot
接口,只需将 调用savefig
为函数来保存最近创建的图形:
import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf') # saves the current figure
回答by joelostblom
You can use ax.figure.savefig()
:
您可以使用ax.figure.savefig()
:
import pandas as pd
s = pd.Series([0, 1])
ax = s.plot.hist()
ax.figure.savefig('demo-file.pdf')
This has no practical benefit over ax.get_figure().savefig()
as suggested in Philip Cloud's answer, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure()
simply returns self.figure
:
ax.get_figure().savefig()
正如 Philip Cloud 的回答所建议的那样,这没有实际好处,因此您可以选择您认为最美观的选项。事实上,get_figure()
只需返回self.figure
:
# Source from snippet linked above
def get_figure(self):
"""Return the `.Figure` instance the artist belongs to."""
return self.figure