【python】解决maplotlib边缘留白太多 |
您所在的位置:网站首页 › sai缩小画布以后出现了边缘线怎么处理 › 【python】解决maplotlib边缘留白太多 |
问题描述
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 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |