Search code examples
pythonmatplotlibplot

Python subplots fixed spacing


I am plotting a 4x3 subplots grid and I would like to have fixed spacing between them. I am using subplots_adjust, see below. However, the figures are arranged uniformly within the overall window and do not have fixed spaces. Thanks for your advice.

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(10,10)

fig, axes = plt.subplots(4, 3)

axes[0, 0].imshow(data)
axes[1, 0].imshow(data)
axes[2, 0].imshow(data)
axes[3, 0].imshow(data)

axes[0, 1].imshow(data)
axes[1, 1].imshow(data)
axes[2, 1].imshow(data)
axes[3, 1].imshow(data)

axes[0, 2].imshow(data)
axes[1, 2].imshow(data)
axes[2, 2].imshow(data)
axes[3, 2].imshow(data)

plt.setp(axes, xticks=[], yticks=[])

plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=.05, hspace=.05)

plt.show()

(Improve subplot size/spacing with many subplots solves overlapping labels, this question specifically relates to constant spacing between subplots)


Solution

  • The problem you face, is that the arguments of subplots_adjust are relative values, i.e. fractions of the figure width and height, see docu, and not absolute values.

    You are plotting 4 rows and 3 columns of squares (10x10) in the "default canvas" (might be 8x6). However, the figure size is defined in width times height, hence columns times rows. So you have to swap rows and columns and change your subplots call to

    fig, axes = plt.subplots(3, 4)
    

    and your spaces will be equal. If not, try adding figsize=(8,6) to set the figure size. Of course, you have the adjust the indices of the imshow lines.
    enter image description here

    As an alternative, you could swap the figsize arguments.