Matplotlib 调整图像子图 hspace 和 wspace [英] Matplotlib adjust image subplots hspace and wspace
问题描述
我正在尝试在 3×3 网格上构建一个包含 9 个图像子图的图形,所有子图都共享 X 或 Y 轴,并且相邻子图之间没有空间.
以下代码添加所需的轴并折叠它们之间的空间.到目前为止,一切都很好:
fig, axes = plt.subplots(ncols=3, nrows=3, sharex=True, sharey=True)fig.subplots_adjust(hspace=0, wspace=0)
然而,在这些图中绘制图像会破坏一切,因为 imshow
改变了子图的纵横比:
img = np.arange(100).reshape(10, 10)对于axes.flat中的ax:ax.imshow(img)
(如果图像太宽,行之间会出现空格而不是列之间的空格
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).
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.
这篇关于Matplotlib 调整图像子图 hspace 和 wspace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!