Joey Fueng
Joey Fueng

Reputation: 115

python Matplotlib tight_layout() never work well

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: enter image description here 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):

enter image description here enter image description here

Upvotes: 1

Views: 6901

Answers (1)

Zephyr
Zephyr

Reputation: 12496

You can set figure layout parameters with subplots_adjust.

Basic Code

import matplotlib.pyplot as plt

N = 5

fig, ax = plt.subplots(N, N)

plt.show()

enter image description here

Complete Code

import matplotlib.pyplot as plt

N = 5

fig, ax = plt.subplots(N, N)

plt.subplots_adjust(left = 0.1, top = 0.9, right = 0.9, bottom = 0.1, hspace = 0.5, wspace = 0.5)

plt.show()

enter image description here


To avoid making too many attempts to set the values of left, top, etc..., I suggest you to plot a figure, press the Configure subplots button:

enter image description here

and manually change the values of those six parameters, until you find a configuration that satisfies you. At this point, you can set those six values directly via code using subplots_adjust.

Upvotes: 5

Related Questions