0

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

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Mo0nKizz
  • 149
  • 7

1 Answers1

0

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

  • Thank you for your feedback. However I have to use add_subfigure (in order to have different background with facecolor). So do you have any ideas to solve this approach ? – Mo0nKizz Mar 01 '23 at 20:50
  • Yeah this is not the solution if you really have to use `.add_subfigure`. However, do you know you can have different background suplots with `ax.set_facecolor()`? In your code it would be `subplots_1.set_facecolor('red')` / `subplots_2.set_facecolor('blue')` for example. – just_another_profile Mar 01 '23 at 20:56
  • set_facecolor only colors the ax but not the entire figure (label, title, ...) – Mo0nKizz Mar 01 '23 at 20:58
  • I see, yeah my solution won't work then. I think changing your question to 'Spacing adjustment for subfigures' to make it super clear that you need subfigures might help you :) – just_another_profile Mar 01 '23 at 21:13
  • Also, on top of my head, there is also `tight_layout` which is different from `contrained_layout` - it might be worth a try? – just_another_profile Mar 01 '23 at 21:16
  • It seems to not solve the issue. – Mo0nKizz Mar 02 '23 at 07:17