Sometimes we would like to create a gird of square images, where each image must keep the equal aspect ratio. Sadly enough, matplotlib is not good at this simple common task, but one way is to use matplotlib.gridspec and specify every parameters manually. This guy presents a nice code sample to calculate relevant parameters semi-automatically, and I modified it for my purpose.
ncol = 8 nrow = math.ceil(number_of_images / ncol) + 1 fig = plt.figure(figsize=(ncol+1, nrow+1)) gs = gridspec.GridSpec(nrow, ncol, wspace=0.1, hspace=0.1, top=1. - 0.5 / (nrow + 1), bottom=0.5 / (nrow + 1), left=0.5 / (ncol + 1), right=1 - 0.5 / (ncol + 1)) for i in range(number_of_images):
n = i // ncol m = i % ncol ax = plt.subplot(gs[n, m]) ax.set_title('') ax.imshow(my_images[i,:,:], interpolation='nearest', cmap="gray") ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_xticks([]) ax.set_yticks([]) plt.savefig(filename)
We can modify "wspace" and "hspace" parameters to adjust spacing between images.