2

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?

gboffi
  • 22,939
  • 8
  • 54
  • 85
  • `plt.colorbar(im, cax=grid.cbar_axes[0], orientation='horizontal')` seems to work here. – JohanC Jun 02 '23 at 10:41
  • @JohanC I confirm your finding, Now, If I could find why it works with `cax=grid.cbar_axes[0]` but silently fails with `cax=grid.cbar_axes[1]`. Nevertheless, if you'd be pleased to post this as an answer... – gboffi Jun 02 '23 at 10:56
  • 1
    I'm not sure what's happening. With `cbar_mode="single"` it seems the first colorbar is changed to cover the desired region and the two other seem to be invisible. Also, the orientation of the colorbar isn't set automatically to horizontal. Feel free to answer your own question. – JohanC Jun 02 '23 at 11:01

1 Answers1

1

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)
Stef
  • 28,728
  • 2
  • 24
  • 52