How to retrieve colorbar instance from figure in matplotlib

Sometimes it can be useful to retrieve a colorbar even if it was not held in a variable.

In this case, it is possible to retrieve the colorbar from the plot with:

# Create an example image and colourbar
img = np.arange(20).reshape(5,4)
plt.imshow(img)
plt.colorbar()

# Get the current axis 
ax = plt.gca()        

# Get the images on an axis
im = ax.images        

# Assume colorbar was plotted last one plotted last
cb = im[-1].colorbar   

# Do any actions on the colorbar object (e.g. remove it)
cb.remove()

EDIT:

or, equivalently, the one liner:

plt.gca().images[-1].colorbar.remove()

N.B.: see also comments for the use of ax.collections[-1] instead of ax.images[-1]. For me it always worked only the first way, I don’t know what depends on, maybe the type of data or plot.


Now you can operate on cb as if it were stored using commands described in the colorbar API. For instance you could change xlim or call update as explained in other comments. You could remove it with cb.remove() and recreate it with plt.colorbar().

plt.draw() or show should be called after to update plot.

As the image is the mappable associated to the colorbar and can be obtained with cb.mappable.

Leave a Comment