pythonmatplotlibmultiple-axes

Proper position for my colorbar in an AxesGrid collocation


enter image description here

The figure above was produced by


import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid

mat = [[1,2],[3,4]]
fig = plt.figure()
grid = AxesGrid(fig, 111, nrows_ncols=(1,3),
       axes_pad=0.2, share_all=False, label_mode='L',
       cbar_location="bottom", cbar_mode="single")
for ax in grid.axes_all: im = ax.imshow(mat)
# plt.colorbar(im, cax=??)
plt.show()

To complete the job, I'd like to draw a colorbar, probably using the Axes at the bottom of the figure (but I'm not sure that using cax=... is what I need),

HOWEVER

I don't know how to recover the bottom Axes from grid.

After dir(grid), I've tried to specify ax=grid.cb_axes but the result is amendable

enter image description here

What must be done to have everything in its right place?


Solution

  • Another (shorter) way is using grid.cbar_axes[0].colorbar(im):

    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import AxesGrid
    
    mat = [[1,2],[3,4]]
    fig = plt.figure()
    grid = AxesGrid(fig, 111, nrows_ncols=(1,3),
           axes_pad=0.2, share_all=False, label_mode='L',
           cbar_location="bottom", cbar_mode="single")
    for ax in grid.axes_all: im = ax.imshow(mat)
    grid.cbar_axes[0].colorbar(im) 
    

    enter image description here

    As JohanC already stated in the comment, with cbar_mode="single", all but the first cbar_axes are set invisible:

        for i in range(self.ngrids):
            self.cbar_axes[i].set_visible(False)
        self.cbar_axes[0].set_axes_locator(locator)
        self.cbar_axes[0].set_visible(True)