2

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()
Jakob
  • 19,815
  • 6
  • 75
  • 94
user2926577
  • 1,717
  • 4
  • 14
  • 16

2 Answers2

3

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.

Jakob
  • 19,815
  • 6
  • 75
  • 94
1

You can control the spacing and position of each subplot directly using gridspec. There's more information here. Here's an example:

import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np

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

plt.figure(figsize = (6,6)) # set the figure size to be square

gs = gridspec.GridSpec(4, 3)
# set the space between subplots and the position of the subplots in the figure
gs.update(wspace=0.1, hspace=0.4, left = 0.1, right = 0.7, bottom = 0.1, top = 0.9) 


for g in gs:
    ax = plt.subplot(g)
    plt.imshow(data)

plt.show()

gridspec example

Molly
  • 13,240
  • 4
  • 44
  • 45