使用Python保存具有精确像素大小的matplotlib图形

6

我想以确切的像素大小保存一个matplotlib图形。在下面的代码中,这个确切的大小是500x500像素。 虽然保存的图像是500x500像素,但它包括围绕我的形状和绘图区域的填充。我希望圆紧贴边框。相反,我的圆周围有白色空间。是否有可能仅保存绘图区域? 请注意,尽管下面的代码是可再现的,但我的_dpi取决于您的显示器DPI。220是我的显示器的DPI。

import matplotlib.pyplot as plt
import matplotlib.image as mpimage
import numpy as np

H       = 500
W       = 500
radius  = H/2
my_dpi  = 220


a = np.deg2rad(0)
b = np.deg2rad(360);

t = np.linspace(a,b,100)
x = radius*np.cos(t)
y = radius*np.sin(t)
x = np.append(x,[0,x[0]])
y = np.append(y,[0,y[0]])

myFig   = plt.figure()
DPI     = my_dpi #myFig.get_dpi()
myFig.set_size_inches(float(H)/float(DPI),float(W)/float(DPI))

plt.fill(y,x,color='none',facecolor='red')
plt.axis((-W/2,W/2,-H/2,H/2))
plt.axis('off')
#plt.show()
plt.savefig('my_fig.png',dpi=DPI)

print 'Figure Size: ', myFig.get_size_inches()

Im = mpimage.imread('my_fig.png')
print 'Im Size: ', Im.shape

可能是在像素级别上指定和保存图形的确切大小的重复问题。 - Paul H
1个回答

5
您可以使用subplots_adjust来设置您的图表周围的填充。
myFig.subplots_adjust(bottom=0.,left=0.,right=1.,top=1.)

enter image description here


这解决了我在使用bbox_inches='tight'隐藏绘图轴时出现的额外空白问题。 - Guillochon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接