在ipython笔记本中,首先创建一个pandas系列对象,然后通过调用实例方法.hist(),浏览器会显示图形。
我想知道如何将这个图形保存到文件中(我的意思是不通过右键另存为,而是在脚本中需要使用的命令)。
使用Figure.savefig()
方法,如下:
ax = s.hist() # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')
不一定要以pdf
形式结束,有很多选项可供选择。请查看文档。
或者,您可以使用pyplot
界面,只需调用savefig
函数即可保存最近创建的图像:
import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf') # saves the current figure
AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'
,那么很可能是在绘制多列。
ax
将是所有轴的数组。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')
你可以使用 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()
相比没有实际好处,因此您可以选择您认为最 esthetically pleasing的选项。事实上,get_figure()
只是返回self.figure
:
# Source from snippet linked above
def get_figure(self):
"""Return the `.Figure` instance the artist belongs to."""
return self.figure
您可以通过以下方式简单地保存您的(例如直方图)绘图:
df.plot.hist().get_figure().savefig('name')
我想强调一下,默认分辨率为100dpi,适合屏幕显示,但如果需要放大或打印,则无法满足要求。您可以传递'dpi'参数以获得高分辨率文件:
ax = s.hist() # s is an instance of Series
ax.figure.savefig('/path/to/figure.png', dpi=300)