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

如何让Matplotlib垂直堆叠子图紧密贴合且无遮挡?

调整Matplotlib垂直堆叠子图间距实现紧密贴合

你当前代码中子图间距过大的核心原因是GridSpec设置了hspace=0.2的间距,同时子图默认边距也会占用额外空间。要实现论文中子图近乎相接的效果,可通过以下步骤调整:

关键调整点

  • 将GridSpec的hspace参数设为0,彻底消除子图间的默认间距
  • 微调坐标轴标签的内边距(labelpad),避免标签跨子图遮挡
  • 确保相邻子图的X轴范围完全一致(已在你的代码中实现),保证对齐精度

修改后的完整代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

years = np.linspace(1300, 2000, 700)
np.random.seed(42)

delta_13C = np.cumsum(np.random.normal(0, 0.1, 700))
delta_13C = delta_13C - np.mean(delta_13C)
delta_18O = np.cumsum(np.random.normal(0, 0.08, 700))
delta_18O = delta_18O - np.mean(delta_18O)
temp_anomaly = np.cumsum(np.random.normal(0, 0.03, 700))
temp_anomaly = temp_anomaly - np.mean(temp_anomaly)
temp_anomaly[-100:] += np.linspace(0, 1.5, 100)

plt.style.use('default')
plt.rcParams['font.size'] = 12
plt.rcParams['axes.linewidth'] = 1.5
plt.rcParams['axes.labelsize'] = 14

fig = plt.figure(figsize=(10, 8))
# 核心修改:将hspace设为0,消除子图间距
gs = GridSpec(3, 1, height_ratios=[1, 1, 1], hspace=0)

ax1 = fig.add_subplot(gs[0])
ax1.plot(years, delta_13C, color='green', linewidth=1.0)
# 减小labelpad避免标签侵入下方子图
ax1.set_ylabel('First', color='green', labelpad=8)
ax1.tick_params(axis='y', colors='green')
ax1.set_xlim(1300, 2000)
ax1.set_ylim(-4, 4)
ax1.xaxis.set_visible(False)
ax1.spines['top'].set_visible(False)
ax1.spines['bottom'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax1.spines['left'].set_color('green')

ax2 = fig.add_subplot(gs[1])
ax2.plot(years, delta_18O, color='blue', linewidth=1.0)
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position("right")
# 减小labelpad避免标签侵入上下子图
ax2.set_ylabel('Second', color='blue', labelpad=8)
ax2.tick_params(axis='y', colors='blue')
ax2.set_xlim(1300, 2000)
ax2.set_ylim(-3, 3)
ax2.xaxis.set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.spines['bottom'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax2.spines['right'].set_color('blue')

ax3 = fig.add_subplot(gs[2])
ax3.plot(years, temp_anomaly, color='gray', linewidth=1.0)
ax3.set_ylabel('Third', color='black', labelpad=8)
ax3.set_xlim(1300, 2000)
ax3.set_ylim(-1.0, 1.5)
ax3.set_xlabel('Year (CE)')
ax3.spines['top'].set_visible(False)
ax3.spines['right'].set_visible(False)

# 可选:使用tight_layout进一步优化整体布局,避免边缘内容被截断
plt.tight_layout()
plt.show()

额外优化建议

如果需要更精细的子图高度控制,可以调整height_ratios参数(比如[1.2, 1, 1]),适配不同子图的数据范围;若出现刻度标签重叠,可通过plt.rcParams['xtick.major.pad']或ytick.major.pad调整刻度的内边距。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 13:05:25