Gridspec 子图出乎意料的不同大小

问题描述 投票:0回答:1

我正在尝试使用 matplotlib 创建图像网格。 第一行和第一列定义函数的输入,网格的其余部分是输出。

这是别人对我希望它的外观的参考:reference.

特别注意将第一行和第一列与其他所有内容分开的行。

过去几个小时我一直在努力让它发挥作用。到目前为止我做得最好的是使用 Gridspec 将图像分成四组并使用 PIL 构建图像。

但是,出于某种原因,我无法理解不同子图的形状不匹配。

附上一个最小的代码和它的输出。

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import PIL

f = plt.figure(figsize=(20, 20))

resolution = 256
num_images = 6
h = w = num_images
main_grid = gridspec.GridSpec(h, w, hspace=0, wspace=0)

col = f.add_subplot(main_grid[0, 1:])
row = f.add_subplot(main_grid[1:, 0])
mid = f.add_subplot(main_grid[1:, 1:])
corner = f.add_subplot(main_grid[0, 0])

corner_canvas = PIL.Image.new('RGB', (resolution, resolution), 'gray')
mid_canvas = PIL.Image.new('RGB', (resolution * w, resolution * h), 'yellow')
col_canvas = PIL.Image.new('RGB', (resolution * w, resolution), 'blue')
row_canvas = PIL.Image.new('RGB', (resolution, resolution * h), 'red')

corner.imshow(corner_canvas)
col.imshow(col_canvas)
row.imshow(row_canvas)
mid.imshow(mid_canvas)

plt.savefig('fig.png')

here

如您所见,形状不匹配,导致网格未对齐。

python image matplotlib grid python-imaging-library
1个回答
0
投票

对于这种布局,我会结合使用

GridSpec
GridSpecFromSubplotSpec

Nx = 2
Ny = 3
sp = 0.5

fig = plt.figure()
gs0 = matplotlib.gridspec.GridSpec(2,2, width_ratios=[1,Nx+1], height_ratios=[1,Ny+1], wspace=sp, hspace=sp, figure=fig)
gs00 = matplotlib.gridspec.GridSpecFromSubplotSpec(1,Nx,subplot_spec=gs0[0,1:], wspace=0, hspace=0)
gs01 = matplotlib.gridspec.GridSpecFromSubplotSpec(Ny,1,subplot_spec=gs0[1:,0], wspace=0, hspace=0)
gs11 = matplotlib.gridspec.GridSpecFromSubplotSpec(Ny,Nx, subplot_spec=gs0[1:,1:], wspace=0, hspace=0)



top_axes = [fig.add_subplot(gs00[i]) for i in range(Nx)]
left_axes = [fig.add_subplot(gs01[i]) for i in range(Ny)]
center_axes = [fig.add_subplot(gs11[j,i]) for j in range(Ny) for i in range(Nx)]

© www.soinside.com 2019 - 2024. All rights reserved.