Handling proportion of subplots in Matplotlib (Python)

Viewed 261

Hi I am trying to create the subplots below using matplotlib.

Subplots

I have the following code but I cant seem to configure the plots correctly using the arguments.Would appreciate for any help on this. Welcome any other plotting tools on python that could help me stitch 4 plots in this manner too.

Thank you so much!

gs1 = fig9.add_gridspec(nrows=8, ncols=8, top=0.6, bottom=0.1,left = 0, right = 0.65,
                        wspace=0.05, hspace=0.05)
# f9_ax1 = fig9.add_subplot(gs1[:-1, :])
ax2 = fig9.add_subplot(gs1[:1, :1])
ax3 = fig9.add_subplot(gs1[:1, 1:])

gs2 = fig9.add_gridspec(nrows=4, ncols=4, top=1.2, bottom=0.4, left = 0, right = 0.5,
                        wspace=0.05, hspace=0.05)
ax4 = fig9.add_subplot(gs1[1: , :1])
ax5 = fig9.add_subplot(gs1[1:, 1:])

The above code gives this enter image description here

2 Answers

You can divide the figure for example in a 20 x 20 grid which means that one cell makes up 5% x 5% of the figure. Scaling your proportions 35/65 -> 7/13, 40/60 -> 8/12 and 50/50 -> 10/10 to this grid gives:

import matplotlib.pyplot as plt

fig = plt.figure(constrained_layout=True)
gs1 = fig.add_gridspec(nrows=20, ncols=20)
 
ax1 = fig.add_subplot(gs1[0:12, 0:7])     # top left     (size: 12x7  - 60x35)
ax2 = fig.add_subplot(gs1[0:12, 7:20])    # top right    (size: 12x13 - 60x65)
ax3 = fig.add_subplot(gs1[12:20, 0:10])   # bottom left  (size: 8x10  - 40x50)
ax4 = fig.add_subplot(gs1[12:20, 10:20])  # bottom right (size: 8x10  - 40x50)

grid spec

Note also the constrained_layout keyword, setting this to True shrinks the subplots to make all axis labels visible, this has the maybe unwanted affect of changing the aspect ratios slightly. When setting it to False the proportions are better preserved. However currently Constrained Layout is experimental and maybe changed or removed.

See also the documentation for more information.

Create 2 separate gridspecs, where you can set the height_ratios to (6, 4) for both, but then give them different width_ratios as required.

For example:

import matplotlib.pyplot as plt

fig = plt.figure()

gs1 = fig.add_gridspec(nrows=2, ncols=2, hspace=0.05, wspace=0.05,
                       height_ratios=(6, 4), width_ratios=(35, 65))
gs2 = fig.add_gridspec(nrows=2, ncols=2, hspace=0.05, wspace=0.05, 
                       height_ratios=(6, 4), width_ratios=(1, 1))

ax1 = fig.add_subplot(gs1[0, 0])
ax2 = fig.add_subplot(gs1[0, 1])
ax3 = fig.add_subplot(gs2[1, 0])
ax4 = fig.add_subplot(gs2[1, 1])

plt.show()

enter image description here

Related