我正在研究一個項目,在這個項目中我需要將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
我明白了。所以「無花果」真的是指整體圖像大小,而不是子圖。我迷惑了自己。 –