'How to add colorbar to existing axis handle?

This way is easy and works:

plt.imshow(im)
plt.colorbar()

But when it's like this:

f,ax = plt.subplots(3,1)
ax[2].imshow(im)

How do I get the colorbar on that axis? I don't need anything fancy, just the defaults.



Solution 1:[1]

Pass the respective image and axes handles into fig.colorbar:

fig, axs = plt.subplots(3, 1)

im2 = axs[2].imshow(im)
fig.colorbar(im2, ax=axs[2])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tdy