【发布时间】:2020-07-16 21:12:32
【问题描述】:
我正在使用 GridSpec 在子图中绘制子图以显示图像。
在下面的示例代码中,我正在创建一个 1x2 子图,其中每个子图轴包含 3x3 子图(第一个子图中的子图)。
3x3 子图基本上显示了将图像切成 9 块排列成 3x3 格式的图像。我不希望图像片段之间有任何间距,因此我将 wspace 和 hspace 都设置为 0。奇怪的是,生成的输出子图显示了行之间的垂直间隙。
我尝试将hspace 设置为负值以减小行之间的垂直间距,但这会导致行重叠。有没有更方便的方法来实现这一点?
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from PIL import Image
from sklearn.datasets import load_sample_image
flower = load_sample_image('flower.jpg')
img = Image.fromarray(flower)
img = img.crop((100, 100, 325, 325))
# Create tiles - cuts image to 3x3 square tiles
n_tiles = 9
tile_size = float(img.size[0]) / 3 # assumes square tile
tiles = [None] * n_tiles
for n in range(n_tiles):
row = n // 3
col = n % 3
# compute tile coordinates in term of the image (0,0) is top left corner of the image
left = col * tile_size
upper = row * tile_size
right = left + tile_size
lower = upper + tile_size
tile_coord = (int(left), int(upper), int(right), int(lower))
tile = img.crop(tile_coord)
tiles[n] = tile
# plot subplot of subplot using gridspec
fig = plt.figure(figsize=(7, 3))
outer = gridspec.GridSpec(1, 3, wspace=1)
# image shown as 3x3 grid of image tiles
inner = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=outer[0], wspace=0, hspace=0)
for j in range(len(tiles_tensor)):
ax1 = plt.Subplot(fig, inner[j], xticks=[], yticks=[])
ax1.imshow(tiles[j])
fig.add_subplot(ax1)
# image shown as 3x3 grid of image tiles
inner = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=outer[1], wspace=0, hspace=0)
for j in range(len(data)):
ax2 = plt.Subplot(fig, inner[j], xticks=[], yticks=[])
ax2.imshow(tiles[j])
fig.add_subplot(ax2)
【问题讨论】:
-
只是把它扔在那里...我更喜欢使用 plt.axes 来制作子图,您可以明确说明大小 plt.axes(left,bottom,width,height)
标签: python matplotlib subplot