Create multiple columns and rows of unequal size in matplotlib

Viewed 532

I need to create multiple columns and rows of unequal size in matplotlib. Here is a sample code:

a = np.random.rand(20, 20)
b = np.random.rand(20, 5)
c = np.random.rand(5, 20)
d = np.random.rand(5,5)
arrays = [a,b,c,d]
fig, axs = plt.subplots(2, 2, sharex='col', sharey= 'row', figsize=(10,10))
for ax, ar in zip(axs.flatten(), arrays):
    ax.imshow(ar)

However, I get this as a result.

python output

The right column has images of unequal width for the first and second row, and I would want them to be equal (basically shrink the bottom right image to have the same scale as other images). I had researched this a fair amount, but nothing seems to work. I had tried tight_layout(), some other formatting tricks, all to no avail...

1 Answers

You can use the gridspec's height_ratios and width_ratios argument to set the desired proportion the subplots shall occupy.

In this case, due to the symmetry, this is simply the shape of e.g. b.

import numpy as np
import matplotlib.pyplot as plt

a = np.random.rand(20, 20)
b = np.random.rand(20, 5)
c = np.random.rand(5, 20)
d = np.random.rand(5,5)
arrays = [a,b,c,d]
fig, axs = plt.subplots(2, 2, sharex='col', sharey= 'row', figsize=(10,10), 
                        gridspec_kw={"height_ratios" : b.shape, 
                                     "width_ratios" : b.shape})
for ax, ar in zip(axs.flatten(), arrays):
    ax.imshow(ar)

plt.show()

enter image description here

Or, more generally,

gridspec_kw={"height_ratios" : [a.shape[0], c.shape[0]], 
              "width_ratios" : [a.shape[1], b.shape[1]]}
Related