remove colorbar from figure in matplotlib

Alright, here's my solution. Not terribly elegant, but not a terrible hack either.

def foo(self):
   self.subplot.clear()
   hb = self.subplot.hexbin(...)
   if self.cb:
      self.figure.delaxes(self.figure.axes[1])
      self.figure.subplots_adjust(right=0.90)  #default right padding
   self.cb = self.figure.colorbar(hb)

This works for my needs since I only ever have a single subplot. People who run into the same problem when using multiple subplots or when drawing the colorbar in a different position will need to tweak.


I managed to solve the same issue using fig.clear() and display.clear_output()

import matplotlib.pyplot as plt
import IPython.display as display
import matplotlib.tri as tri
from pylab import *
%matplotlib inline

def plot_res(fig):
    ax=fig.add_axes([0,0,1,1])
    ax.set_xlabel("x")
    ax.set_ylabel('y')
    plotted=ax.imshow(rand(250, 250))
    ax.set_title("title")
    cbar=fig.colorbar(mappable=plotted)
    display.clear_output(wait=True)
    display.display(plt.gcf())
    fig.clear()

fig=plt.figure()
N=20
for j in range(N):
    plot_res(fig)

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