3
f = plt.figure(figsize=(12,10))

ax1 = f.add_subplot(411)
ax2 = f.add_subplot(422)
ax3 = f.add_subplot(423)
ax4 = f.add_subplot(424)
ax5 = f.add_subplot(425)
ax6 = f.add_subplot(426)
ax7 = f.add_subplot(427)
ax8 = f.add_subplot(428)

I want to increase space between two rows: ax1 and ax2-ax3. Other spaces should remain the same. Using "f.subplots_adjust(hspace = 0.2, wspace= 0.25)" adjusts the spacing for all subplots. What can I do to increase hspace for the top-most subplot only?

enter image description here

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

2 Answers2

1
import matplotlib.pyplot as plt 

fig, axs = plt.subplot_mosaic([['top', 'top'],['left1', 'right1'], ['left2', 'right2']], 
                              constrained_layout=True)
axs['top'].set_xlabel('Xlabel\n\n')
plt.show()

This will make all the y-axes the same size. If that is not important to you, then @r-beginners answer is helpful. Note that you need-not use subplot mosaic, though it is a useful new feature.

enter image description here

If you are not worried about the axes sizes matching, then a slightly better way than proposed above is to use the new subfigure functionality:

import matplotlib.pyplot as plt 

fig = plt.figure(constrained_layout=True)

subfigs = fig.subfigures(2, 1, height_ratios=[1, 2], hspace=0.15)

# top 
axtop = subfigs[0].subplots()

# 2x2 grid
axs = subfigs[1].subplots(2, 2)

plt.show()

enter image description here

Jody Klymak
  • 4,979
  • 2
  • 15
  • 31
0

Based on the gridspec sample in the official reference, I customized it using this example answer.The point is to use gridspec for the separate graphs you want to configure.

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec


def format_axes(fig):
    for i, ax in enumerate(fig.axes):
        ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
        ax.tick_params(labelbottom=False, labelleft=False)

fig = plt.figure()

gs_top = GridSpec(3, 3, top=0.95)
gs_base = GridSpec(3, 3)
ax1 = fig.add_subplot(gs_top[0, :])
# identical to ax1 = plt.subplot(gs.new_subplotspec((0, 0), colspan=3))
ax2 = fig.add_subplot(gs_base[1, :-1])
ax3 = fig.add_subplot(gs_base[1:, -1])
ax4 = fig.add_subplot(gs_base[-1, 0])
ax5 = fig.add_subplot(gs_base[-1, -2])

# fig.suptitle("GridSpec")
format_axes(fig)

plt.show()

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32