首页 > 解决方案 > Matplotlib Subplots are jammed together

问题描述

I have modeled mnist dataset and the test set (x_test) is of length 2000 digit images and the model predicts wrong on the images with indices wrong_predicted_images in test set. I am trying to plot the images along with the correct labels ( from test set: y_test). I came up with this. However, when I plot it, all the images are gets jammed together.

num_cols = 5
num_images = len(wrong_predicted_images)
num_rows = num_images//num_cols +1
f, axarr = plt.subplots(num_rows, num_cols, sharex='col', sharey='row')
f.subplots_adjust(hspace=1,wspace= 1) # to have space between images
for count, i in enumerate(wrong_predicted_images):
  x, y = count//num_cols, count % num_cols
  axarr[x,y].imshow(x_test[i])
  axarr[x,y].imshow(x_test[i])
  axarr[x,y].set_title(y_test[i], loc = 'right')
  plt.grid(False)
plt.show()

Here is the produced image

enter image description here

How can I fix this?

标签: pythonmatplotlib

解决方案


我的猜测是你试图在一个图中绘制太多图像,在下面我将使用 9 与 299 图像来模拟你的过程,第二个图与你所展示的可疑地相似......</p>

In [26]: import matplotlib.pyplot as plt 
    ...: import numpy as np 
    ...: img = np.arange(54*108).reshape(108,54)                                          

In [27]: N = 9 
    ...: nc = 5 
    ...: nr = (N-1)//nc + 1 
    ...: f, axarr = plt.subplots(nr, nc, sharex='col', sharey='row') 
    ...: f.subplots_adjust(hspace=1, wspace=1) 
    ...: for c in range(N): 
    ...:     x, y = c//nc, c%nc 
    ...:     axarr[x,y].imshow(img) 
    ...:     axarr[x,y].set_title('title')

在此处输入图像描述

In [28]: N = 299 
    ...: nc = 5 
    ...: nr = (N-1)//nc + 1 
    ...: f, axarr = plt.subplots(nr, nc, sharex='col', sharey='row') 
    ...: f.subplots_adjust(hspace=1, wspace=1) 
    ...: for c in range(N): 
    ...:     x, y = c//nc, c%nc 
    ...:     axarr[x,y].imshow(img) 
    ...:     axarr[x,y].set_title('title')                                                

在此处输入图像描述


推荐阅读