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

使用AxesGrid时图像显示异常,如何实现无截断并排显示?

修复AxesGrid图像显示截断问题

原代码及问题

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid

mat0 = [[1, 2], [3, 4], [5, 6], [7, 8]] # 4行×2列
mat1 = [[-2, 0, 2, 4], [0, 2, 4, 6]]    # 2行×4列

fig = plt.figure(figsize=(9, 3))
grid = AxesGrid(fig, 111, nrows_ncols=(1,2),
                axes_pad=0.15,
                cbar_size="6%", cbar_location="right", cbar_mode="single")
for ax, mat in zip(grid.axes_all, (mat0, mat1)): im = ax.imshow(mat)
grid.cbar_axes[0].colorbar(im)

plt.figure()
plt.imshow(mat0)
plt.colorbar()

plt.show()

运行代码后生成两个Figure:

  • 第一个Figure中,左侧对应mat0的高矩形图像被截断,无法完整显示
  • 第二个Figure中,mat0的图像能正常完整显示

需求是让第一个Figure里的左右两个图像并排完整显示,左侧为mat0的高矩形,右侧为mat1的宽矩形,右侧附带共用颜色条。

问题原因

AxesGrid默认强制所有子图使用相同的宽高比,而mat0(4行2列)和mat1(2行4列)的高宽比差异较大,导致mat0的图像被裁剪以适配统一的宽高比。

解决方案

方案1:使用ImageGrid(推荐,专为图像布局设计)

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

mat0 = [[1, 2], [3, 4], [5, 6], [7, 8]] # 4行×2列
mat1 = [[-2, 0, 2, 4], [0, 2, 4, 6]]    # 2行×4列

fig = plt.figure(figsize=(9, 3))
grid = ImageGrid(fig, 111, nrows_ncols=(1,2),
                 axes_pad=0.15,
                 cbar_size="6%", cbar_location="right", cbar_mode="single")

for ax, mat in zip(grid, (mat0, mat1)):
    # 设置aspect='auto'让图像自适应子图空间,取消固定宽高比约束
    im = ax.imshow(mat, aspect='auto')

grid.cbar_axes[0].colorbar(im)

plt.figure()
plt.imshow(mat0)
plt.colorbar()

plt.show()

方案2:修改AxesGrid子图参数

如果坚持使用AxesGrid,需手动取消子图的固定宽高比约束:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid

mat0 = [[1, 2], [3, 4], [5, 6], [7, 8]] # 4行×2列
mat1 = [[-2, 0, 2, 4], [0, 2, 4, 6]]    # 2行×4列

fig = plt.figure(figsize=(9, 3))
grid = AxesGrid(fig, 111, nrows_ncols=(1,2),
                axes_pad=0.15,
                cbar_size="6%", cbar_location="right", cbar_mode="single")

for ax, mat in zip(grid.axes_all, (mat0, mat1)):
    im = ax.imshow(mat)
    ax.set_aspect('auto')  # 取消固定宽高比
    ax.set_adjustable('datalim')  # 让子图尺寸适配数据范围

grid.cbar_axes[0].colorbar(im)

plt.figure()
plt.imshow(mat0)
plt.colorbar()

plt.show()

两种方案都能让两个图像按自身尺寸完整显示,并排布局且共用右侧颜色条。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 20:05:42