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

Matplotlib mosaic布局下colorbar间距与对齐异常问题咨询

Matplotlib子图与Colorbar布局异常原因解析

问题现象

运行提供的代码后,出现两个明显布局问题:

  • 左上角子图(A)的图像与colorbar间距,和右上角子图(B)的对应间距不一致
  • 底部跨列子图(C)的colorbar,无法与右上角子图(B)的colorbar水平对齐

原因说明

1. 左右子图colorbar间距差异

使用constrained布局时,Matplotlib会自动为子图分配空间容纳colorbar。左侧子图(A)的colorbar位于其右侧,布局引擎需要在A和B之间挤出空间放置;而右侧子图(B)的colorbar处于布局最右边缘,直接使用右侧额外空间,两者的空间分配逻辑不同,最终导致间距出现差异。

2. 跨列子图colorbar无法对齐

子图C是横跨两列的大子图,它的colorbar默认垂直放置在自身右边缘,这个位置基于两列宽度的子图边界;而子图B的colorbar基于单宽度子图的右边缘,两者水平基准不同,自然无法对齐。

修正方案示例

使用mpl_toolkits.axes_grid1.make_axes_locatable可以统一控制colorbar的尺寸和间距,让布局更规整:

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

matrix = np.random.rand(100, 100)

mosaic = "AB;CC"
    
fig = plt.figure(layout="constrained")
ax_dict = fig.subplot_mosaic(mosaic)

# 统一设置colorbar的尺寸和间距
def add_colorbar(ax):
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    img = ax.imshow(matrix, aspect="auto")
    fig.colorbar(img, cax=cax)

add_colorbar(ax_dict['A'])
add_colorbar(ax_dict['B'])
add_colorbar(ax_dict['C'])

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 10:34:52