Colorer placement for imshow with aspect

Hi,

I have a problem placing the colorbar next to an imshow when I specify an aspect ratio. Below is a minimal example showing my problem where the colorbar in the first plot looks good while in the second there is far too much whitespace between the figure and the colorbar. I have looked at Overview of axes_grid1 toolkit — Matplotlib 3.3.4 documentation but can’t seem to figure out how to make it look good.

Any help appreciated,
Erik

import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable

img_file = ‘https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Cat-relaxed.jpg/640px-Cat-relaxed.jpg
img = plt.imread(img_file, format=‘jpg’)

cmap = cm.Blues

plt.figure(10, clear=True)
ax = plt.subplot()
im = ax.imshow(img, aspect=1)
divider = make_axes_locatable(ax)
cax = divider.append_axes(“right”, size=“5%”, pad=0.05)
plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=cax)

plt.figure(20, clear=True)
ax = plt.subplot()
im = ax.imshow(img, aspect=3)
divider = make_axes_locatable(ax)
cax = divider.append_axes(“right”, size=“5%”, pad=0.05)
plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=cax)
plt.show()

aspect ratios and colorbars are problematic because colorbars are placed relative to the size of the axes before the aspect ratio is applied. i.e. think of the axes as the big thing that the axes with the set aspect ratio is placed inside.

On the other, hand, I think a reasonable approach is

plt.figure(20, clear=True)
ax = plt.subplot()
im = ax.imshow(img, aspect=3)
cax = ax.inset_axes([1.02, 0, 0.05, 1.], transform=ax.transAxes)
plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=cax)
plt.show()

Figure_20

Thank you! This I would not have figured out for myself.

Best,
Erik