Spacing adjustment for gridspec subfigures

135 Views Asked by At

I wanted to change the size of hspace on my figure without using constrained_layout=True.

Here is my code:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np

fig = plt.figure()
# fig = plt.figure(constrained_layout=True)
GridSpec = gridspec.GridSpec(ncols=1, nrows=2, figure= fig, hspace=0.9)

subfigure_1= fig.add_subfigure(GridSpec[0,:])
subplots_1= subfigure_1.subplots(1,1)

subfigure_2= fig.add_subfigure(GridSpec[1,:])
subplots_2= subfigure_2.subplots(1,1)

plt.show()

With constrained_layout=True, it works but sometimes I am faced other issues that I don't want with this setting set to True. (Moreover it seems that constrained_layout=True disables width_ratios on gridSpec.)

1

There are 1 best solutions below

6
just_another_profile On

You can change it using hspace however fig.add_subfigure and the .suplots in your code was confusing gridspec on how to construct the figure and apply hspace. Instead you can call gridspec by using fig.add_subplot directly (I'm using hspace=0.1 so that the change is obvious):

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

fig = plt.figure()
GridSpec = gridspec.GridSpec(ncols=1, nrows=2, figure=fig, hspace=0.1)

subplots_1 = fig.add_subplot(GridSpec[0, :])
subplots_2 = fig.add_subplot(GridSpec[1, :])

plt.show()

enter image description here