Search code examples
pythonmatplotlibsubplotcolorbaraxes

How to keep nested axes position while using subplots_adjust


I use the following code to add a colorbar at the top left corner of each subplot.

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)

which gives the following plot: enter image description here

However, if I use the subplots_adjust() function (by replacing False to True in the code above), the colorbars do not move properly: enter image description here

Do you know how I can handle it?


Solution

  • Using the inset_axes() function from the mpl_toolkits module solves the problem. It is also possible to simply use ax.inset_axes().

    Here is the new code:

    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)
    

    Here is the result: enter image description here