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

使用Matplotlib的GridSpec与colorbar时宽度比例异常问题

解决GridSpec布局被Colorbar打乱的问题

核心问题

使用plt.colorbar()默认方式时,Matplotlib会自动调整当前Axes的位置以容纳colorbar,这会破坏GridSpec预设的width_ratios,导致布局偏移。要解决这个问题,需要为colorbar单独预留GridSpec单元格,并通过fig.colorbar()的cax参数指定其位置。

修正后的代码

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

data1 = np.random.rand(10,10)
data2 = np.random.rand(10,10)
x = np.linspace(1,10,10)

fig = plt.figure(constrained_layout=True)
# 第一行3列(colorbar1, 二维图1, 一维图),第二行2列(二维图2, colorbar2)
gs = GridSpec(2, 3, figure=fig, width_ratios=[1, 10, 2])

# 第一行:左侧colorbar,中间二维图,右侧一维图
cax1 = fig.add_subplot(gs[0, 0])
ax1 = fig.add_subplot(gs[0, 1])
img1 = ax1.imshow(data1, aspect='auto')
fig.colorbar(img1, cax=cax1, orientation='vertical')

ax2 = fig.add_subplot(gs[0, 2])
ax2.plot(x, data1[0,:])

# 第二行:二维图占前两列,右侧colorbar占第三列
ax3 = fig.add_subplot(gs[1, :2])
img2 = ax3.imshow(data2, aspect='auto')
cax2 = fig.add_subplot(gs[1, 2])
fig.colorbar(img2, cax=cax2, orientation='vertical')

plt.show()

关键修改点

  • 重新规划GridSpec结构:第一行分3列,为第一个colorbar、二维图、一维图分配不同宽度比例,让一维图更靠右;第二行分2列,二维图占左侧大部分空间,colorbar在右侧。
  • 指定colorbar的位置:通过fig.add_subplot()为每个colorbar创建专属Axes(cax1、cax2),再用fig.colorbar(img, cax=...)将colorbar绑定到该Axes,避免自动调整布局。
  • 取消location参数:不再依赖plt.colorbar()的location自动布局,完全由GridSpec控制位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 01:33:32