可以通过savefig()方法,将绘制的图形保存为文件:
x = np.linspace(0,10,100) fig = plt.figure() plt.plot(x,np.sin(x),'-') plt.plot(x,np.cos(x),'--') fig.savefig('d:/my_fig.png')
然后通过IPython的Image来显示文件内的图像:
from IPython.display import Image Image('d:/my_fig.png')
可以通过下面的方法查看系统支持的图片格式:
>>> fig.canvas.get_supported_filetypes() {'ps': 'Postscript', 'eps': 'Encapsulated Postscript', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'jpg': 'Joint Photographic Experts Group', 'jpeg': 'Joint Photographic Experts Group', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format'}
savefig方法有一些可定制的参数,比如你想得到一个600dpi的图片,并且尽量少的空白:
plt.savefig('image_name.png', dpi=600,bbox_inches='tight')
savefig也可以写入到文件对象中,比如BytesIO:
from io import BytesIO buffer = BytesIO() plt.savefig(buffer) plot_data = buffer.getvalue()
下面是savefig方法的参数说明: