Skip to content Skip to sidebar Skip to footer

Matplotlib Adjust Image Subplots Hspace And Wspace

I’m trying to build a figure with 9 image subplots on a 3×3 grid, all sharing X or Y axes, and with no space between adjacent subplots. The following code adds the required axi

Solution 1:

Partial answer for 2×2 grids

It is possible to use ax.set_anchor to align each image within its assigned space:

fig, axes = plt.subplots(ncols=2, nrows=2, sharex=True, sharey=True)
fig.subplots_adjust(hspace=0, wspace=0)
axes[0, 0].set_anchor('SE')
axes[1, 0].set_anchor('NE')
axes[0, 1].set_anchor('SW')
axes[1, 1].set_anchor('NW')
img = np.arange(100).reshape(10, 10)
for ax in axes.flat:
    ax.imshow(img)

2×2 image subplots grid with no space between the images

This works also for the wider aspect ratio, but it breaks down for grids that are wider or taller than 2 axes.

Solution 2:

You can specify the figure size so that it will have a different aspect ratio; in this case a square:

import numpy as np
from matplotlib import pyplot as plt    

fig, axes = plt.subplots(ncols=3, nrows=3, sharex=True, sharey=True, figsize=(5,5))
fig.subplots_adjust(hspace=0, wspace=0)

img = np.arange(100).reshape(10, 10)
for ax in axes.flat:
    ax.imshow(img)
plt.show()

It's not the most flexible solution, but it's a fairly straightforward solution.

enter image description here

Post a Comment for "Matplotlib Adjust Image Subplots Hspace And Wspace"