Gridspec subplots unexpected different size

Question:

I am trying to create a grid of images using matplotlib.
The first row and column define the input to a function and the rest of the grid is the output.

Here’s someone else’s reference of how I would like it to look: reference.

Especially note that lines seperating the first row and column from everything else.

I was trying for the last couple of hours to make it work. The best I’ve come so far is using Gridspec to divide the image into four groups and construct the image using PIL.

However, for a reason I cannot understand the shapes of the different subplots don’t match.

Attaching a minimal code and it’s output.

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

As you can see, the shapes don’t match, which make the grid not aligned.

Asked By: Yotam Nitzan

||

Answers:

I would use a combination of GridSpec and GridSpecFromSubplotSpec for this kind of layout:

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)]

enter image description here

Answered By: Diziet Asahi