【问题标题】:save a pandas.Series histogram plot to file将 pandas.Series 直方图保存到文件
【发布时间】:2013-09-30 06:54:06
【问题描述】:
在ipython Notebook中,首先创建一个pandas Series对象,然后调用实例方法.hist(),浏览器显示图形。
我想知道如何将此图保存到文件中(我的意思不是右键单击并另存为,而是脚本中需要的命令)。
【问题讨论】:
标签:
python
pandas
histogram
【解决方案1】:
您可以像这样简单地保存您的(例如直方图)图:
df.plot.hist().get_figure().savefig('name')
【解决方案2】:
只是想补充一点,默认分辨率是 100dpi,这对屏幕来说很好,但如果你想放大或打印它就不行了。您可以传递 'dpi' 参数来获取高分辨率文件:
ax = s.hist() # s is an instance of Series
ax.figure.savefig('/path/to/figure.png', dpi=300)
【解决方案3】:
使用Figure.savefig() 方法,如下所示:
ax = s.hist() # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')
它不必以pdf 结尾,有很多选择。查看the documentation。
或者,您可以使用pyplot 接口并将savefig 作为函数调用以保存最近创建的图形:
import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf') # saves the current figure
多列绘图
- 添加自 2018 年 5 月 11 日发表的评论 toto_tico
- 如果您收到此错误
AttributeError: 'numpy.ndarray' object has no attribute 'get_figure',那么您很可能正在绘制多个列。
ax = s.hist(columns=['colA', 'colB'])
# try one of the following
fig = ax[0].get_figure()
fig = ax[0][0].get_figure()
fig.savefig('figure.pdf')
【解决方案4】:
你可以使用ax.figure.savefig():
import pandas as pd
s = pd.Series([0, 1])
ax = s.plot.hist()
ax.figure.savefig('demo-file.pdf')
正如 Philip Cloud 的回答中所建议的那样,这与 ax.get_figure().savefig() 相比没有实际好处,因此您可以选择您认为最美观的选项。其实get_figure() simply returns self.figure:
# Source from snippet linked above
def get_figure(self):
"""Return the `.Figure` instance the artist belongs to."""
return self.figure