Python中Matplotlib保存图像时去除边框的方法

直接说解决方法:

plt.savefig(‘image3.png’,bbox_inches=‘tight’,pad_inches=0)

(三行搞定)

import numpy as np
import matplotlib.pyplot as plt

img = np.random.randn(10,10)

fig=plt.imshow(img)
plt.axis('off')
plt.savefig('image3.png',bbox_inches='tight',pad_inches=0)

解决问题的步骤

网上的方法大多使用这个套路

import numpy as np
import matplotlib.pyplot as plt 

img = np.random.randn(10,10)

fig=plt.imshow(img)
plt.axis('off')
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, 
             hspace = 0, wspace = 0)           
plt.margins(0,0)
plt.savefig('image3.png')

这样保存下来的图像有透明边框

在上述代码中的plt.savefig中加入bbox_inches='tight’得到的图如下

去除了大部分透明边框,但仍然有小部分透明边框

查阅savefig函数的默认参数:

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)

发现自带了0.1的padding,加上之后:

物联沃分享整理
物联沃-IOTWORD物联网 » Python中Matplotlib保存图像时去除边框的方法

发表评论