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