问题
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 axis and collapses the space between them. So far, so good:
fig, axes = plt.subplots(ncols=3, nrows=3, sharex=True, sharey=True)
fig.subplots_adjust(hspace=0, wspace=0)
However, plotting images inside these plots breaks everything, because imshow
changes the aspect ratio of the subplots:
img = np.arange(100).reshape(10, 10)
for ax in axes.flat:
ax.imshow(img)
(If the image is too wide, you get spaces between rows instead of columns as shown on this figure.)
Question: how to make a figure containing image subplots with no space between adjacent axes, regardless of the aspect ratio of the images?
What can’t be an answer:
- Cropping the images
- Changing their aspect ratio (mandatory XKCD).
回答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)
This works also for the wider aspect ratio, but it breaks down for grids that are wider or taller than 2 axes.
回答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.
来源:https://stackoverflow.com/questions/52661906/matplotlib-adjust-image-subplots-hspace-and-wspace