Summary: I want to use Matplotlib.tight_layout() to automatically optimize the layout of figures that contains any number of subfigures with 2D numpy.array.
Example: Here is an example (the data can be accessed from http://www.filedropper.com/fmap). I want to plot the feature map of an CNN layer (later I want to make this automatic, so the code can plot feature maps of any layer from any model). Here I only show the code for one layer for demonstration:
fmap.shape # (1, 64, 64, 128)
square1 = int(round(math.sqrt(fmap.shape[-1])/8)*8) # 8
square2 = int(fmap.shape[-1]/square1) # 16
ix = 1
for _ in range(square1):
for _ in range(square2):
# specify subplot and turn of axis
ax = plt.subplot(square1, square2, ix)
ax.set_xticks([])
ax.set_yticks([])
# plot filter channel in grayscale
plt.imshow(fmap[0, :, :, ix-1], cmap='gray')
ix += 1
# show the figure
plt.tight_layout()
plt.show()
The plot is shown as:
The space between subfigures and the margin are quite random, as can be seen from feature maps of different layers (the number of subplot differs):





matplotlib.pyplot.tight_layout. Try using therectparameter. It's expected that the padding is dependant upon the number of subplots and the figure size and will be different depending on the configuration.imshowwhich defaults toaspect='equal', always showing square images when x and y dimensions are equal. If you really want tight layout, you either need to set a suitable figure width and height, or useimshow(..., aspect='auo')(which stretches the images to fit into the desired layout).