Python Matplotlib 中如何用 plt.savefig 存储图片

前言

函数包名:import matplotlib.pyplot as plt

正文

主要功能:保存绘制数据后创建的图形。使用此方法可以将创建的图形保存

函数源码:(根据需要进行选择)

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)

参数解释:

参数 描述 fname 指定格式图片或者指定文件位置 dpi 画质 facecolor 和 edgecolor 默认为白色 Orientation 横向或者纵向 papertype 纸张类型 format 如png、pdf transparent 图片背景透明 bbox_inches 图表多余的空白区去除 pad_inches 保存图形周围填充

正常保存:plt.savefig("xx.png"),也可以svg的格式进行保存

保存的时候需要plt.show()在plt.savefig()之后,顺序颠倒会出现图片为空白。

当前文件保存:

注意事项:

    如果plt.show() 在plt.savefig()前,就会导致保存图片是空白的情况。 window的路径读取,需要反斜杠

要把所有的参数用上,可以用在直方图上

import matplotlib.pyplot as plt

x =[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
plt.hist(x)
  
plt.savefig("squares1.png",
            bbox_inches ="tight",
            pad_inches = 1,
            transparent = True,
            facecolor ="g",
            edgecolor =w,
            orientation =landscape)
  
plt.show()
经验分享 程序员 微信小程序 职场和发展