如何使用 Matplotlib 将绘图保存到文件中?
Matplotlib 是一个广泛使用的Python库,用于绘制图形、绘图、图表等。 show() 方法用于将图形显示为输出,但不要将其保存在任何文件中。要将生成的图形保存在存储磁盘上的文件中,请使用 savefig() 方法。
savefig() :保存当前图形。
Syntax: pyplot.savefig(fname, dpi=None, facecolor=’w’, edgecolor=’w’, orientation=’portrait’, papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None, metadata=None)
Parameters:
- fname : path or name of output file with extension. If extension is not provided plot is saved as png file. Supported file formats: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff.
- dpi : dots per inch resolution of figure
- facecolor : facecolor of figure
- edgecolor : edgecolor of figure
- orientation : landscape or portrait
- format : The file format, e.g. ‘png’, ‘pdf’, ‘svg’, etc.
- transparent : If it is True, the patches of axes will all be transparent
脚步:
- 绘制图形
- 使用 pyplot.savefig() 方法将生成的绘图保存在文件中
例子:
Python3
import matplotlib.pyplot as plt
# Creating data
year = ['2010', '2002', '2004', '2006', '2008']
production = [25, 15, 35, 30, 10]
# Plotting barchart
plt.bar(year, production)
# Saving the figure.
plt.savefig("output.jpg")
# Saving figure by changing parameter values
plt.savefig("output1", facecolor='y', bbox_inches="tight",
pad_inches=0.3, transparent=True)
输出: