Matplotlib约束布局下移除子图间空白(保留约束布局且不使用bbox_inches='tight')
如何在保留约束布局(constrained layout)且不使用
bbox_inches='tight'的前提下移除子图间空白? 你当前的代码启用了Matplotlib的约束布局,但两个子图之间仍存在多余空白。核心问题在于约束布局会接管间距管理,同时子图内的元素(如下方表格)和默认边距会额外占用空间。以下是针对性的解决方案:
修改后的代码
import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD')) fig = plt.figure(layout="constrained", figheight=5, figwidth=5) # 通过高度比例分配子图空间,适配上方绘图区和下方表格 gs1 = gridspec.GridSpec(2, 1, figure=fig, height_ratios=[1, 3]) ax1 = fig.add_subplot(gs1[0]) ax2 = fig.add_subplot(gs1[1], sharex=ax1) # 让表格完全填满ax2子图区域 ax2.table(cellText=df.values, colLabels=df.columns, rowLabels=['Something', '1','2','3','4', '5','6','7','8','9'], loc='center', bbox=[0, 0, 1, 1]) # 强制表格占满子图范围 ax2.axis('off') # 移除ax1的x轴、底部边框,并消除上下边距 ax1.xaxis.set_visible(False) ax1.spines['bottom'].set_visible(False) ax1.margins(y=0) # 清除ax1的上下冗余边距 # 强制设置子图间垂直间距为0 gs1.update(hspace=0) plt.show()
关键改动说明
- 适配子图高度比例:用
height_ratios合理分配两个子图的高度,避免上方子图预留过多空白,同时给表格足够的显示空间。 - 表格填满子图:给
table添加bbox=[0,0,1,1]参数,让表格完全覆盖ax2区域,消除表格周围的空白。 - 清除ax1冗余元素:隐藏x轴和底部边框,并用
margins(y=0)去掉上下边距,减少子图底部的空白。 - 强制压缩子图间距:通过
gs1.update(hspace=0)进一步约束垂直方向的空白,配合约束布局实现无缝衔接。
内容的提问来源于stack exchange,提问作者Juniper
相关产品推荐
相关产品推荐

