You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何缩小matplotlib add_gridspec创建的子图间间距

解决Matplotlib Gridspec子图间距过大的问题

我使用Matplotlib的add_gridspec配合Seaborn绘制多子图布局,设置了宽度比例widths = [4, 1, 4, 1],但右侧主图(axs[6])和旁边的子图(axs[7])之间间距明显过大;添加ylabel或放大刻度字号后,间距会进一步变宽,即便移除这些设置,基础间距仍不符合预期。

示例代码

fig = plt.figure(figsize=(15,8))

widths = [4, 1, 4, 1]
heights = [1, 4]

# Gridspec preparation
spec = fig.add_gridspec(ncols=4, nrows=2, width_ratios=widths, height_ratios=heights)

# Setting axes
axs = {}
for i in range(len(heights)*len(widths)):
    axs[i] = fig.add_subplot(spec[i//len(widths), i%len(widths)])
    axs[i].text(0.5, 0.5, f"axs[{i}]", fontdict=dict(ha="center", color="k", fontsize=20))

# 疑似引发间距问题的代码段
for i,a in enumerate([axs[4], axs[6]]):
    a.set_ylabel("GAP CREATOR?", fontsize=20)
    a.tick_params(length=20, width=2, labelsize=20, direction="in", which="major")
    a.grid(ls="--")
fig.tight_layout()

解决方案

  • 改用Gridspec的wspace参数控制间距
    tight_layout()会自动为带标签的子图预留空间,打乱预设的宽度比例。可以移除fig.tight_layout(),直接在add_gridspec中设置列间距:

    spec = fig.add_gridspec(ncols=4, nrows=2, width_ratios=widths, height_ratios=heights, wspace=0.1)
    

    根据需求调整wspace的数值(比如0.05到0.2之间),直到间距符合预期。

  • 隐藏不需要的标签减少空间占用
    如果部分子图不需要y轴标签或刻度,直接隐藏它们,避免tight_layout为其预留额外空间:

    # 隐藏右侧辅助子图的y轴元素
    for ax in [axs[5], axs[7]]:
        ax.set_yticklabels([])
        ax.set_ylabel("")
    

    这样即使保留tight_layout(),也不会因为空白标签浪费空间。

  • 手动调整子图位置
    针对个别间距问题,直接修改子图的位置参数进行精细调整:

    # 调整主图axs[6]的宽度,缩小与右侧子图的间距
    pos = axs[6].get_position()
    axs[6].set_position([pos.x0, pos.y0, pos.width * 1.05, pos.height])
    
    # 对应调整右侧子图axs[7]的位置
    pos7 = axs[7].get_position()
    axs[7].set_position([pos7.x0 - 0.03, pos7.y0, pos7.width * 0.9, pos7.height])
    

搜索关键词参考

如果需要查找更多相关方案,可以用这些关键词:

  • matplotlib gridspec reduce column spacing
  • matplotlib tight_layout override width ratios
  • matplotlib adjust subplot spacing manually

内容的提问来源于stack exchange,提问作者huon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:15:00