remove colorbar from figure in matplotlib
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:
- holding the colorbar in a value at the moment of creation, as shown in other answers e.g.
cb=plt.colorbar()
- retrieve an existing colorbar, that you can do following (and upvoting :)) what I wrote here: How to retrieve colorbar instance from figure in matplotlibthen:
cb.remove()plt.draw() #update plot
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 pltimport IPython.display as displayimport matplotlib.tri as trifrom pylab import *%matplotlib inlinedef 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=20for j in range(N): plot_res(fig)