您当前的位置: 首页 >  Python

Xavier Jiezou

暂无认证

  • 2浏览

    0关注

    394博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【python】解决maplotlib边缘留白太多

Xavier Jiezou 发布时间:2020-11-23 18:37:30 ,浏览量:2

问题描述

maplotlib绘图边缘留白太多:

import matplotlib.pyplot as plt
plt.subplot(221, fc='r')
plt.subplot(222, fc='g')
plt.subplot(223, fc='b')
plt.subplot(224, fc='c')
plt.savefig('test.jpg')
plt.show()

在这里插入图片描述

解决方案

使用plt.savefig方法保存图片时,设置bbox_inches参数为tight(紧凑型):

import matplotlib.pyplot as plt
plt.subplot(221, fc='r')
plt.subplot(222, fc='g')
plt.subplot(223, fc='b')
plt.subplot(224, fc='c')
plt.savefig('test.jpg', bbox_inches='tight')
plt.show()

在这里插入图片描述

拓展阅读

查阅官方文档可知,当设置bbox_inches参数为tight时,边缘留白也就是边框的宽度你可以通过设置pad_inches的值来自定义,默认是0.1(单位:英寸) 在这里插入图片描述

import matplotlib.pyplot as plt
plt.subplot(221, fc='r')
plt.subplot(222, fc='g')
plt.subplot(223, fc='b')
plt.subplot(224, fc='c')
plt.savefig('test.jpg', bbox_inches='tight', pad_inches=1)
plt.show()

在这里插入图片描述

注意事项

bbox_inches='tight'的缺点是会导致对输出图片的大小设置失效。

以上图为例,设置画布大小为10英寸 x 10英寸,保存dpi设置为100像素/英寸,那么保存的图片大小就是1000像素 x 1000像素

import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
plt.subplot(221, fc='r')
plt.subplot(222, fc='g')
plt.subplot(223, fc='b')
plt.subplot(224, fc='c')
plt.savefig('test.jpg', dpi=100)
plt.show()

但是引入bbox_inches='tight'后,我们发现对输出图片大小的设置已经失效了,实际输出图片大小为837像素 x 819像素

import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
plt.subplot(221, fc='r')
plt.subplot(222, fc='g')
plt.subplot(223, fc='b')
plt.subplot(224, fc='c')
plt.savefig('test.jpg', bbox_inches='tight', dpi=100)
plt.show()
温馨提示

如果完全不想留白,并且想保留对输出图片大小的设置,那么可以添加plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)plt.margins(0, 0)

import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
plt.subplot(221, fc='r')
plt.subplot(222, fc='g')
plt.subplot(223, fc='b')
plt.subplot(224, fc='c')
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
plt.margins(0, 0)
plt.savefig('test.jpg', dpi=100)
plt.show()
引用参考

https://matplotlib.org/api/_as_gen/matplotlib.pyplot.savefig.html https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.margins.html https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots_adjust.html

关注
打赏
1661408149
查看更多评论
立即登录/注册

微信扫码登录

0.0621s