28

I have a matplotlib plot in python with 3 subplots, all in 1 column.

I currently control the height of each subplot with:

gridspec.GridSpec(3, 1, height_ratios=[1, 3, 3])

I have no spacing via:

plt.subplots_adjust(hspace=0.0)

But I would like to put some spacing between row 2 and 3 only.

In one of the other answers, I read that I can do something like:

gs1.update(left=0.05, right=0.48, wspace=0)

But I don't really understand what is happening. Could someone give me some more information please?

user1551817
  • 6,693
  • 22
  • 72
  • 109

3 Answers3

32

When you call update, you're applying those parameters to all of the subplots in that particular gridspec. If you want to use different parameters for different subplots, you can make multiple gridspecs. However, you'll need to make sure they are the correct size and don't overlap. One way do to that is with nested gridspecs. Since the total height of the bottom two plots is 6 times the top, the outer gridspec will have a height ratio of [1, 6].

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


def do_stuff(cell): #just so the plots show up
    ax = plt.subplot(cell)
    ax.plot()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
plt.subplots_adjust(hspace=0.0)
#make outer gridspec
outer = gridspec.GridSpec(2, 1, height_ratios = [1, 6]) 
#make nested gridspecs
gs1 = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec = outer[0])
gs2 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec = outer[1], hspace = .05)
for cell in gs1:
    do_stuff(cell)
for cell in gs2:
    do_stuff(cell)
plt.show()

Plot with three subplots

Amy Teegarden
  • 3,842
  • 20
  • 23
15

In this particular case it's probably quickest to just add an invisible axes object between rows 2 and 3:

import matplotlib.pyplot as plt

gridspec = dict(hspace=0.0, height_ratios=[1, 1, 0.4, 3])
fig, axs = plt.subplots(nrows=4, ncols=1, gridspec_kw=gridspec)
axs[2].set_visible(False)

I looked through the documentation and it appears that variable grid spacing is not supported. So we have to make do with workarounds like this one.

subplots

Joooeey
  • 3,394
  • 1
  • 35
  • 49
  • Genius, saved my day! I already had like 30 axe objects floating around and now starting with GridSpec seemed that I had to start from scratch on that figure. This was so easy, just make a few more axe objects as spacers! – fratajcz Aug 04 '22 at 10:24
0

You can use gridspec and define an extra subplot without content and give it a small width ratio depending on the space you want to exist between the other subplots.

spec = gridspec.GridSpec(ncols=4, nrows=1, figure=fig,width_ratios=[1,1,0.4,2])
ax00  = fig.add_subplot(spec[0, 0])
ax01  = fig.add_subplot(spec[0, 1])
ax03  = fig.add_subplot(spec[0, 3])

In my example 02 subplot is used only for spacing with a width ratio of 0.4 :).