Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I increase Horizontal Space (hspace) between two specific matplotlib subplots?

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

like image 777
Tanvir Alam Shifat Avatar asked Dec 21 '25 07:12

Tanvir Alam Shifat


1 Answers

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

like image 87
Jody Klymak Avatar answered Dec 22 '25 21:12

Jody Klymak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!