如何在使用 subplots_adjust 时保持嵌套轴的位置

How to keep nested axes position while using subplots_adjust

我使用以下代码在每个子图的左上角添加一个颜色条。

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 ********
    # Define position of the desired colorbar in axes coordinate 
    # [(lower left x, lower left y), (upper right x, upper right y)]
    ax_coord = [(0.05, 0.5), (0.2, 0.95)]

    # Transform the two points from axes coordinates to display coordinates
    tr1 = ax.transAxes.transform(ax_coord)

    # Create an inverse transversion from display to figure coordinates
    inv = fig.transFigure.inverted()
    tr2 = inv.transform(tr1)

    # Position in figure coordinates [left, bottom, width, height]
    datco = [tr2[0,0], tr2[0,1], tr2[1,0]-tr2[0,0], tr2[1,1]-tr2[0,1]]

    # Create colorbar axes
    cbar_ax = fig.add_axes(datco)

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

if False:
    plt.subplots_adjust(left=0.15, bottom=0.2, right=0.95, top=0.8)

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

给出了以下情节:

但是,如果我使用 subplots_adjust() 函数(通过将上面代码中的 False 替换为 True),颜色条不会正确移动:

你知道我怎么处理吗?

使用 mpl_toolkits 模块中的 inset_axes() 函数解决了问题。也可以简单地使用 ax.inset_axes().

这是新代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

# 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)

    axins = inset_axes(ax, width="5%", height="50%", loc='upper left')

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

if True:
    plt.subplots_adjust(left=0.15, bottom=0.2, right=0.95, top=0.8)

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

结果如下: