Python中的 Matplotlib.pyplot.savefig()
Matplotlib 是Python中非常有用的可视化库。它是一个基于 NumPy 数组构建的多平台数据可视化库,旨在与更广泛的 SciPy 堆栈一起使用。可视化起着非常重要的作用,因为它可以帮助我们理解大量数据并提取知识。
Matplotlib.pyplot.savefig()
顾名思义,savefig() 方法用于保存绘制数据后创建的图形。使用此方法可以将创建的图形保存到我们的本地机器。
Syntax: 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 | DESCRIPTION |
---|---|
fname | Filename .png for image, .pdf for pdf format. File location can also be specified here. |
dpi | Number of dots per inch.(picture quality) |
papertype | Paper type could be “a0 to a10”, “executive”, “b0 to b10”, “letter”, “legal”, “ledger”. |
format | File format such as .png, .pdf. |
facecolor and edgecolor | Default as White. |
bbox_inches | Set it as “tight” for proper fit of the saved figure. |
pad_inches | Padding around the saved figure. |
transparent | Makes background of the picture transparent. |
Orientation | Landscape or Portrait. |
示例 1:
# importing required modules
import matplotlib.pyplot as plt
# creating plotting data
xaxis =[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
yaxis =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# plotting
plt.plot(xaxis, yaxis)
plt.xlabel("X")
plt.ylabel("Y")
# saving the file.Make sure you
# use savefig() before show().
plt.savefig("squares.png")
plt.show()
输出 :
示例 2:
# importing the modules
import matplotlib.pyplot as plt
# creating data and plotting a histogram
x =[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
plt.hist(x)
# saving the figure.
plt.savefig("squares1.png",
bbox_inches ="tight",
pad_inches = 1,
transparent = True,
facecolor ="g",
edgecolor ='w',
orientation ='landscape')
plt.show()
输出 :