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

Matplotlib:多子图共享色条时的tight_layout布局异常问题

解决Matplotlib多子图共享色条时tight_layout布局异常问题

你的问题出在:使用plt.gca()获取了第二个子图作为分割对象,给它附加色条轴后压缩了该子图尺寸,再加上plt.tight_layout()的自动调整,导致两个子图尺寸不一致。以下是两种可行的解决方案:

方法一:使用fig.colorbar统一放置色条(推荐)

这种方式无需修改子图结构,直接在画布上添加色条并关联所有子图,布局更规整:

import matplotlib.pyplot as plt
import numpy as np

plt.close('all')
arr = np.arange(100).reshape((10, 10))
fig, ax = plt.subplots(ncols=2, figsize=(8, 4))
im0 = ax[0].imshow(arr, interpolation="none")
im1 = ax[1].imshow(arr, interpolation='none')

# 关联所有子图添加色条,控制宽度和间距
cbar = fig.colorbar(im0, ax=ax, fraction=0.05, pad=0.05)

plt.tight_layout()
plt.show()
  • ax=ax指定色条与所有子图关联,保证子图尺寸统一
  • fraction参数控制色条相对子图的宽度,pad控制色条与子图的间距

方法二:调整make_axes_locatable与tight_layout的配合

如果坚持使用axes_grid1工具,需要手动给tight_layout预留色条空间,避免布局冲突:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

plt.close('all')
arr = np.arange(100).reshape((10, 10))
fig, ax = plt.subplots(ncols=2, figsize=(8, 4))
im0 = ax[0].imshow(arr, interpolation="none")
im1 = ax[1].imshow(arr, interpolation='none')

# 针对第二个子图分割出色条轴
divider = make_axes_locatable(ax[1])
cax = divider.append_axes("right", size="5%", pad="3%")
fig.colorbar(im0, cax=cax)

# 手动设置tight_layout的边界,给色条留出右侧空间
fig.tight_layout(rect=[0, 0, 0.95, 1])
plt.show()
  • rect=[0, 0, 0.95, 1]表示tight_layout只调整画布左侧95%的区域,右侧5%留给色条
  • 避免直接用plt.tight_layout(),改用fig.tight_layout()并指定边界参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 00:10:33