【问题标题】:How can I increase Horizontal Space (hspace) between two specific matplotlib subplots?如何增加两个特定 matplotlib 子图之间的水平空间(hspace)?
【发布时间】:2021-06-27 00:40:33
【问题描述】:
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)

我想增加两行之间的空间:ax1 和 ax2-ax3。其他空间应保持不变。使用“f.subplots_adjust(hspace = 0.2, wspace= 0.25)”调整所有子图的间距。我该怎么做才能只增加最顶层子图的 hspace?

【问题讨论】:

  • 一个技巧是在ax2的标题上加一个空格,即ax2.set_title(“”),然后使用constrained_layout

标签: matplotlib subplot


【解决方案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()

这将使所有 y 轴大小相同。如果这对您不重要,那么@r-beginners 的回答很有帮助。请注意,您不需要使用子图马赛克,尽管它是一个有用的新功能。

如果您不担心轴大小匹配,那么比上面建议的更好的方法是使用新的子图功能:

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

【讨论】:

    【解决方案2】:

    基于官方reference中的gridspec示例,我使用此示例answer对其进行了自定义。重点是要对要配置的单独图表使用gridspec。

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

    【讨论】: