消除Matplotlib GridSpec子图间的空白间距
问题:Matplotlib GridSpec布局子图间距过大,无法填满绘图区域
我尝试用Matplotlib创建第一列含3个子图、第二列含2个子图的布局,通过GridSpec设置后子图间存在较大空白间距,无法填满整个绘图区域。
当前尝试代码:
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec fig = plt.figure(figsize=(7, 7.5)) gs = gridspec.GridSpec(6, 2) # Top left subplot ax = fig.add_subplot(gs[0:1, 0]) ax.set_ylabel('YLabel0') ax.set_xlabel('XLabel0') # Center left subplot ax = fig.add_subplot(gs[2:3, 0]) ax.set_ylabel('YLabel1') ax.set_xlabel('XLabel1') # Bottom left subplot ax = fig.add_subplot(gs[4:5, 0]) ax.set_ylabel('YLabel2') ax.set_xlabel('XLabel2') # Top right subplot ax = fig.add_subplot(gs[0:2, 1]) ax.set_ylabel('YLabel3') ax.set_xlabel('XLabel3') # Bottom right subplot ax = fig.add_subplot(gs[3:5, 1]) ax.set_ylabel('YLabel4') ax.set_xlabel('XLabel4') plt.show()
运行结果:
问题原因
- GridSpec被设置为6行2列,但子图仅占据了
gs[0:1,0]、gs[2:3,0]、gs[4:5,0]等不连续的行索引,第1、3、5行完全空置,这些空行直接造成了子图间的大段空白。 - 左右列子图的高度分配不匹配:第一列每个子图仅占1行,第二列每个占2行,再加上空行的存在,导致整体布局松散,无法填满画布。
解决建议及修改代码
方法1:调整GridSpec行分配,消除空行
让第一列3个子图和第二列2个子图的高度刚好填满6行网格:第一列每个子图占2行(3×2=6),第二列每个子图占3行(2×3=6),再通过tight_layout()自动消除剩余小间距。
修改后代码:
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec fig = plt.figure(figsize=(7, 7.5)) gs = gridspec.GridSpec(6, 2) # 第一列3个子图,各占2行 ax = fig.add_subplot(gs[0:2, 0]) ax.set_ylabel('YLabel0') ax.set_xlabel('XLabel0') ax = fig.add_subplot(gs[2:4, 0]) ax.set_ylabel('YLabel1') ax.set_xlabel('XLabel1') ax = fig.add_subplot(gs[4:6, 0]) ax.set_ylabel('YLabel2') ax.set_xlabel('XLabel2') # 第二列2个子图,各占3行 ax = fig.add_subplot(gs[0:3, 1]) ax.set_ylabel('YLabel3') ax.set_xlabel('XLabel3') ax = fig.add_subplot(gs[3:6, 1]) ax.set_ylabel('YLabel4') ax.set_xlabel('XLabel4') # 自动调整子图间距,消除多余空白 plt.tight_layout() plt.show()
方法2:使用subplot_mosaic(Matplotlib 3.3+)
用更直观的布局语法定义子图位置,避免手动计算GridSpec索引出错:
import matplotlib.pyplot as plt fig = plt.figure(figsize=(7, 7.5)) # 用mosaic矩阵直观描述布局:左列3个、右列2个的高度对应关系 mosaic = [ ["left_top", "right_top"], ["left_top", "right_top"], ["left_mid", "right_top"], ["left_mid", "right_bottom"], ["left_bottom", "right_bottom"], ["left_bottom", "right_bottom"], ] ax_dict = fig.subplot_mosaic(mosaic) # 设置各子图标签 ax_dict["left_top"].set_ylabel('YLabel0') ax_dict["left_top"].set_xlabel('XLabel0') ax_dict["left_mid"].set_ylabel('YLabel1') ax_dict["left_mid"].set_xlabel('XLabel1') ax_dict["left_bottom"].set_ylabel('YLabel2') ax_dict["left_bottom"].set_xlabel('XLabel2') ax_dict["right_top"].set_ylabel('YLabel3') ax_dict["right_top"].set_xlabel('XLabel3') ax_dict["right_bottom"].set_ylabel('YLabel4') ax_dict["right_bottom"].set_xlabel('XLabel4') plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Jes
相关产品推荐
相关产品推荐

