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

调用subplots_adjust时如何保持子图嵌套axes的位置不变

matplotlib子图嵌套colorbar随subplots_adjust同步移动的解决方案

问题原因

你当前的实现是预先将子图相对坐标转换为固定的画布绝对坐标创建colorbar轴,调用subplots_adjust调整子图位置后,子图的画布坐标发生了变化,但colorbar轴的绝对坐标不会同步更新,因此出现位置偏移。

解决方案

直接使用matplotlib内置的Axes.inset_axes方法创建嵌套轴,该方法天生绑定父轴的相对坐标系统,父轴位置变化时嵌套轴会自动同步调整相对位置,无需手动做坐标转换。

修改后完整代码

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

# Create figure
fig = plt.figure(figsize=(5, 2))

# Specify geometry of the grid for subplots
gs0 = gridspec.GridSpec(1, 3, wspace=0.7)

# Data
a = np.arange(3*5).reshape(3,5)

for ax_i in range(3):
    # Create axes
    ax = plt.subplot(gs0[ax_i])

    # Plot data
    plot_pcolor = plt.pcolormesh(a)

    # ******** Plot a nested colorbar inside the plot ********
    # 直接基于父轴相对坐标创建嵌套轴,参数格式为[左边界x, 下边界y, 宽度, 高度],所有值都是父轴相对坐标
    # 对应你原来的需求:x从0.05到0.2,y从0.5到0.95,所以宽度0.15,高度0.45
    cbar_ax = ax.inset_axes([0.05, 0.5, 0.15, 0.45])

    # Plot colorbar
    cbar = plt.colorbar(plot_pcolor, cax=cbar_ax)
    # ********************************************************

# 现在开启subplots_adjust也不会导致colorbar偏移
plt.subplots_adjust(left=0.15, bottom=0.2, right=0.95, top=0.8)

plt.savefig('test.png', dpi=500)

效果说明

修改后无论是否调用subplots_adjust、调整任意子图边距参数,colorbar都会始终保持在所属子图左上角的对应相对位置,不会出现偏移。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:27:01