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

Matplotlib如何仅在特定两列子图间调整垂直间距?

当然可以实现,推荐两种实用方法:

方法一:用GridSpec精准控制列间距

这种方式能灵活调整特定列之间的间隙,适合精细布局需求:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(22, 10))
# 创建2行3列的网格布局,指定各列宽度比例
gs = gridspec.GridSpec(2, 3, width_ratios=[0.7, 0.7, 1])

# 先给所有列设置一个较小的基础间距(对应第1、2列之间的紧凑效果)
gs.update(wspace=0.1)

# 手动调整第三列子图的位置,拉大它和第二列的间距
for row in range(2):
    ax = fig.add_subplot(gs[row, 2])
    pos = ax.get_position()
    # 偏移量可以自己调,这里设0.06仅供参考
    ax.set_position([pos.x0 + 0.06, pos.y0, pos.width, pos.height])

# 给前两列添加子图
for row in range(2):
    for col in range(2):
        fig.add_subplot(gs[row, col])

方法二:创建子图后调整特定列位置

如果已经用plt.subplots生成了子图数组,直接修改第三列子图的位置更省事:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(
    nrows=2, ncols=3, figsize=(22, 10), gridspec_kw={'width_ratios': [0.7, 0.7, 1]}
)
# 先执行tight_layout处理基础布局,避免标签、标题重叠
plt.tight_layout()

# 遍历第三列的两个子图,把它们向右挪一点,增大和第二列的间距
for i in range(2):
    current_pos = ax[i, 2].get_position()
    # 偏移量按需调整,这里0.05的效果可供参考
    ax[i, 2].set_position([current_pos.x0 + 0.05, current_pos.y0, current_pos.width, current_pos.height])

两种方法都能满足你的需求——第1、2列保持紧凑,只在第2、3列之间加额外间距,选哪种看你代码习惯就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:13:14