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

Matplotlib(GridSpec)子图轴标签被截断?已尝试tight_layout

解决GridSpec子图共享色条时tight_layout()无效的轴标签截断问题

我懂你这种头疼的情况——用GridSpec搭子图加共享色条时,tight_layout()经常会掉链子,明明按网上说的试了还是解决不了轴标签截断的问题。别慌,我给你几个亲测有效的方案:


方案1:手动调整子图边界(最直接)

直接用plt.subplots_adjust()手动控制整个布局的边界,给色条和轴标签留出足够空间,完全绕开tight_layout()的局限性:

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

# 创建画布和GridSpec布局
fig = plt.figure(figsize=(10, 8))
gs = GridSpec(2, 2, figure=fig)

# 添加子图
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, 0])
ax4 = fig.add_subplot(gs[1, 1])

# 绘制示例数据
data = np.random.randn(20, 20)
im1 = ax1.imshow(data)
_ = ax2.imshow(data)
_ = ax3.imshow(data)
_ = ax4.imshow(data)

# 添加共享色条
cbar = fig.colorbar(im1, ax=[ax1, ax2, ax3, ax4], location='right')

# 手动调整布局参数:left/right/bottom/top控制整体边界,wspace/hspace控制子图间距
plt.subplots_adjust(left=0.08, right=0.85, bottom=0.08, top=0.95, wspace=0.2, hspace=0.2)
plt.show()

你可以根据自己的画布尺寸,微调left/right这些参数,直到轴标签和色条都显示正常。


方案2:配合colorbar的pad参数+tight_layout的rect参数

如果还是想保留tight_layout()的自动调整能力,可以给色条设置pad控制间距,同时用rect参数告诉tight_layout()要避开色条的区域:

# 子图创建和绘图代码同方案1

# 添加色条时设置pad,控制色条与子图的距离
cbar = fig.colorbar(im1, ax=[ax1, ax2, ax3, ax4], location='right', pad=0.05)

# rect参数格式是[left, bottom, right, top],这里把右侧15%的空间留给色条
fig.tight_layout(rect=[0, 0, 0.85, 1])
plt.show()

方案3:用GridSpec专门预留色条位置(最灵活)

直接在GridSpec里给色条单独分一列/一行,让tight_layout()能识别到所有元素,自动完成布局:

fig = plt.figure(figsize=(10, 8))
# 创建3列GridSpec,最后一列宽度仅为前两列的1/20,专门放色条
gs = GridSpec(2, 3, figure=fig, width_ratios=[1, 1, 0.05])

# 子图占用前两列
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, 0])
ax4 = fig.add_subplot(gs[1, 1])

# 绘制数据
data = np.random.randn(20, 20)
im1 = ax1.imshow(data)
_ = ax2.imshow(data)
_ = ax3.imshow(data)
_ = ax4.imshow(data)

# 在预留的第三列添加色条
cbar_ax = fig.add_subplot(gs[:, 2])
fig.colorbar(im1, cax=cbar_ax)

# 现在可以正常使用tight_layout()了
fig.tight_layout()
plt.show()

方案4:用make_axes_locatable工具(适配复杂布局)

如果你的子图高度不一致,这个工具能帮你创建和子图高度匹配的色条,同时自动调整布局:

from mpl_toolkits.axes_grid1 import make_axes_locatable

fig = plt.figure(figsize=(10, 8))
gs = GridSpec(2, 2, figure=fig)

ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, 0])
ax4 = fig.add_subplot(gs[1, 1])

data = np.random.randn(20, 20)
im1 = ax1.imshow(data)
_ = ax2.imshow(data)
_ = ax3.imshow(data)
_ = ax4.imshow(data)

# 基于任意一个子图创建色条轴,这里选ax4
divider = make_axes_locatable(ax4)
cbar_ax = divider.append_axes("right", size="5%", pad=0.05)
fig.colorbar(im1, cax=cbar_ax)

# 可选:隐藏多余的轴标签让布局更整洁
for ax in [ax1, ax2, ax3]:
    ax.xaxis.set_ticklabels([])
    ax.yaxis.set_ticklabels([])

fig.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:55:48