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

如何在Matplotlib中为子图设置差异化行间距?

为Matplotlib子图设置不同行间距的解决方案

要实现不同行之间的差异化水平间距,plt.subplots_adjust的全局hspace参数无法满足需求,推荐使用GridSpec来实现细粒度的布局控制,以下是具体实现步骤:

方法:嵌套GridSpec分组控制间距

通过将子图分成不同的行组,分别设置组内和组间的间距,就能实现你要的效果:

  1. 导入依赖库
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
  1. 创建画布并定义主布局与嵌套布局
# 设置画布大小
fig = plt.figure(figsize=(8, 10))

# 主GridSpec:将画布分为上下两大块,高度比例3:1,块间间距设为0.5
main_gs = GridSpec(2, 1, height_ratios=[3, 1], hspace=0.5)

# 上块嵌套3行子GridSpec,行内间距设为0.05
gs_top = main_gs[0].subgridspec(3, 1, hspace=0.05)
# 下块嵌套1行子GridSpec
gs_bottom = main_gs[1].subgridspec(1, 1)
  1. 添加子图并优化显示
# 为每个子GridSpec添加子图
ax1 = fig.add_subplot(gs_top[0])
ax2 = fig.add_subplot(gs_top[1])
ax3 = fig.add_subplot(gs_top[2])
ax4 = fig.add_subplot(gs_bottom[0])

# 隐藏上方子图的x轴刻度,让紧凑间距更直观
ax1.set_xticklabels([])
ax2.set_xticklabels([])
ax3.set_xticklabels([])

# 给子图添加标题方便区分
ax1.set_title("第1行")
ax2.set_title("第2行")
ax3.set_title("第3行")
ax4.set_title("第4行")

plt.show()

原理说明

  • 主GridSpec负责控制第3行与第4行之间的大间距(0.5),通过hspace参数设置块间距离;
  • 上块的嵌套GridSpec负责控制第1-2、2-3行之间的紧凑间距(0.05),通过自身的hspace参数设置组内行间距;
  • 这种分组方式可以轻松扩展到更多行的差异化间距需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:27:33