How to retrieve colorbar instance from figure in matplotlib

Wins picture Wins · Nov 6, 2013 · Viewed 16.3k times · Source

all. I want to update the colorbar of a figure when the imagedata is changed. So something like:

img = misc.lena()
fig = plt.figure()
ax = plt.imshow(im)
plt.colorbar(ax)
newimg = img+10*np.randn(512,512)

def update_colorbar(fig,ax,newimg):
    cbar = fig.axes[1]
    ax.set_data(newimg)
    cbar.update_normal(ax)
    plt.draw()

but it seems that returned results from fig.axes() does not have the colorbar instance like I expected. I can probably just pass the colorbar instance as an argument to the update function, but I thought just passing one fig parameter may be good enough. Can anyone explain a little bit on how to retrieve the colorbar from the figure? Or why 'fig.axes()' doesn't return the AxesImage or Colobar instance but just the Axes or AxesSubplot? I think I just need more understanding of the Axes/Figure stuff.Thank you!

Answer

Vincenzooo picture Vincenzooo · Dec 3, 2015

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.