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

如何使用matplotlib gridspec绘制主图填满空间的多面板图

问题根源

主绘图区无法占满分配的网格空间,是imshow()的aspect参数导致的:你当前手动设置了aspect=(6/4),matplotlib会强制绘图轴保持这个宽高比例,不会拉伸到填满gridspec划分给它的全部区域,哪怕wspace和hspace都设为0也会留空。

修复方法
  • 把imshow的aspect参数改为auto,让图像自动适配轴的尺寸,完全占满分配的网格空间
  • (可选)开启布局自动适配,避免刻度、标签占用空间导致的子图边缘错位

修改后的核心代码段:

import h5py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import transforms
from matplotlib.transforms import Affine2D
import matplotlib.gridspec as gridspec
from FUNCION import *
from FUNCIONAVG import *

f = h5py.File('Datos1', 'r')
print(f.keys())
data = np.array(f['default'])

# 开启constrained_layout自动适配子图间距,避免手动调整的错位问题
fig = plt.figure(1, figsize=(5, 5), constrained_layout=True)
gs = gridspec.GridSpec(8, 8, figure=fig)
gs.update(wspace=0, hspace=0)

# 左侧纵向折线图
ax_left = fig.add_subplot(gs[0:6, 0:2])
base = ax_left.transData
rot = transforms.Affine2D().rotate_deg(90)
ax_left.plot(sum, transform=rot + base)
ax_left.set_ylabel("Y Label")
ax_left.set_xticklabels([])

# 中间主imshow绘图区
ax_main = fig.add_subplot(gs[0:6, 2:6])
# 关键修改:aspect设为auto,让图像填满整个轴区域
ax_main.imshow(data, aspect='auto')
ax_main.set_yticklabels([])

# 底部横向折线图
ax_bottom = fig.add_subplot(gs[6:8, 2:6])
ax_bottom.plot(avg)

plt.savefig("multipanel.png", dpi=300, bbox_inches='tight')
plt.show()

补充说明:如果需要保持imshow显示内容本身的像素比例、避免拉伸变形,可以调整gridspec的行/列宽比例和数据维度匹配,不要手动给imshow设置固定aspect值,这样既能保证内容不变形,也能填满分配的网格空间。

内容的提问来源于stack exchange,提问作者Javier Gómez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 01:04:07