我正在研究一个项目,在这个项目中我需要将10行和3列的小区网格放在一起。尽管我已经能够制作情节和安排子情节,但是我无法制作出没有空白的情节,例如gridspec documentatation以下的情节。 。如何删除matplotlib.pyplot中的子图之间的空间?
我尝试了以下文章,但仍然无法完全移除示例图像中的空白区域。有人可以给我一些指导吗?谢谢!
下面是我的代码。 The full script is here on GitHub。 注意:images_2和images_fool都是具有形状(1032,10)的平展图像的数组,而delta是形状(28,28)的图像数组。
def plot_im(array=None, ind=0):
"""A function to plot the image given a images matrix, type of the matrix: \
either original or fool, and the order of images in the matrix"""
img_reshaped = array[ind, :].reshape((28, 28))
imgplot = plt.imshow(img_reshaped)
# Output as a grid of 10 rows and 3 cols with first column being original, second being
# delta and third column being adversaril
nrow = 10
ncol = 3
n = 0
from matplotlib import gridspec
fig = plt.figure(figsize=(30, 30))
gs = gridspec.GridSpec(nrow, ncol, width_ratios=[1, 1, 1])
for row in range(nrow):
for col in range(ncol):
plt.subplot(gs[n])
if col == 0:
#plt.subplot(nrow, ncol, n)
plot_im(array=images_2, ind=row)
elif col == 1:
#plt.subplot(nrow, ncol, n)
plt.imshow(w_delta)
else:
#plt.subplot(nrow, ncol, n)
plot_im(array=images_fool, ind=row)
n += 1
plt.tight_layout()
#plt.show()
plt.savefig('grid_figure.pdf')
像魔术一样工作,感谢@ImportanceOfBeingErnest!只是想知道为什么你用figsize =(4,10)而不是figsize =(10,10)......后者立即带回空间。 –
如果您的行数多于列数的3倍,为什么还需要一个方形图大小?您当然可以将它设置为(10,10),然后再次调整“左”和“右”参数。我选择'figsize =(4,10)'的想法更多的是拥有'n'行和'm'列,图形大小为(m + 1,n)可能是合适的。其余的则通过微调子图参数来完成。 – ImportanceOfBeingErnest
我明白了。所以“无花果”真的是指整体图像大小,而不是子图。我迷惑了自己。 –