【4.3】matplotlib-savefig(保存图片)

一、查看可保存图片类型

print(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'}

二、figure.Figure.savefig()

图片展示的正常,但是savefig以后,label不在保存的图片中。通过bbox_inches=“tight"来调节

plt.savefig('myfile.png', bbox_inches="tight")

原理:

transparent=True makes the background of the saved figure transparent if the format supports it.
dpi=80 controls the resolution (dots per square inch) of the output.

bbox_inches="tight" fits the bounds of the figure to our plot.

三、调整

有3个因素决定了图片的大小(并不是MPL的特性):

  • 图片尺寸的大小,包含:inches, cm, pt, etc,例如: 5"x7”\ * Size in pixels: e.g. 800x600 pixels\
  • 每个尺寸的像素点 ,Dots per inch (dpi) e.g. 100 dpi

3.1 修改尺寸:

fig = matplotlib.pyplot.gcf()
fig.set_size_inches(18.5, 10.5)
fig.savefig('test2png.png', dpi=100)

## 如果是改变已有的gui windows,则需要加参数forward=True
fig.set_size_inches(18.5, 10.5, forward=True)

3.2 如果修改绘图区域的大小尺寸 ( plotting area )

from matplotlib.pyplot import subplots_adjust
subplots_adjust(left=0.15,bottom=0.1,top=0.9,right=0.95,hspace=0.2,wspace=0.25)

参考资料

药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn