Search code examples
pythonmatplotlibplotsubplot

How to adjust space between every second row of subplots in matplotlib


I'm hoping to adjust the space between subplots horizontally. Specifically between every second row. I can adjust every row using fig.subplots_adjust(hspace=n). But is it possible to apply this to every 2nd row?

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize = (10,10))
plt.style.use('ggplot')
ax.grid(False)

ax1 = plt.subplot2grid((5,2), (0, 0))
ax2 = plt.subplot2grid((5,2), (0, 1))
ax3 = plt.subplot2grid((5,2), (1, 0))  
ax4 = plt.subplot2grid((5,2), (1, 1))
ax5 = plt.subplot2grid((5,2), (2, 0))
ax6 = plt.subplot2grid((5,2), (2, 1)) 
ax7 = plt.subplot2grid((5,2), (3, 0))
ax8 = plt.subplot2grid((5,2), (3, 1))

fig.subplots_adjust(hspace=0.9)

Using the subplots below I'm hoping to add a space between rows 2 and 3 and keep the rest as is. enter image description here


Solution

  • You may interlace two grids such that there is a larger spacing between every second subplot.

    To illustrate the concept:

    enter image description here

    import matplotlib.pyplot as plt
    from matplotlib.gridspec import GridSpec
    
    n = 3 # number of double-rows
    m = 2 # number of columns
    
    t = 0.9 # 1-t == top space 
    b = 0.1 # bottom space      (both in figure coordinates)
    
    msp = 0.1 # minor spacing
    sp = 0.5  # major spacing
    
    offs=(1+msp)*(t-b)/(2*n+n*msp+(n-1)*sp) # grid offset
    hspace = sp+msp+1 #height space per grid
    
    gso = GridSpec(n,m, bottom=b+offs, top=t, hspace=hspace)
    gse = GridSpec(n,m, bottom=b, top=t-offs, hspace=hspace)
    
    fig = plt.figure()
    axes = []
    for i in range(n*m):
        axes.append(fig.add_subplot(gso[i]))
        axes.append(fig.add_subplot(gse[i]))
    
    plt.show()
    

    enter image description here