Search code examples
pythonmatplotlibcolorbar

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

  • 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])