Remove colorbar from figure

I think the problem is that with del you cancel the variable, but not the referenced object colorbar.
If you want the colorbar to be removed from plot and disappear, you have to use the method remove of the colorbar instance and to do this you need to have the colorbar in a variable, for which you have two options:

  1. holding the colorbar in a value at the moment of creation, as shown in other answers e.g. cb=plt.colorbar()
  2. retrieve an existing colorbar, that you can do following (and upvoting :)) what I wrote here: How to retrieve colorbar instance from figure in matplotlib
    then:

cb.remove() plt.draw() #update plot


Full code and result:

from matplotlib import pyplot as plt 
import numpy as np

plt.ion() 
plt.imshow(np.random.random(15).reshape((5,3))) 
cb = plt.colorbar() 
plt.savefig('test01.png') 
cb.remove() 
plt.savefig('test02.png')

test01.png test02.png

Leave a Comment