This should be easy but I'm having a hard time with it. Basically, I have a subplot in matplotlib that I'm drawing a hexbin plot in every time a function is called, but every time I call the function I get a new colorbar, so what I'd really like to do is update the colorbar. Unfortunately, this doesn't seem to work since the object the colorbar is attached to is being recreated by subplot.hexbin.
def foo(self): self.subplot.clear() hb = self.subplot.hexbin(...) if self.cb: self.cb.update_bruteforce() # Doesn't work (hb is new) else: self.cb = self.figure.colorbar(hb)
I'm now in this annoying place where I'm trying to delete the colorbar axes altogether and simply recreate it. Unfortunately, when I delete the colorbar axes, the subplot axes don't reclaim the space, and calling self.subplot.reset_position() isn't doing what I thought it would.
def foo(self): self.subplot.clear() hb = self.subplot.hexbin(...) if self.cb: self.figure.delaxes(self.figure.axes[1]) del self.cb # TODO: resize self.subplot so it fills the # whole figure before adding the new colorbar self.cb = self.figure.colorbar(hb)
Does anyone have any suggestions?
Much appreciated! Adam
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.
The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot indicating the color scale. Syntax:matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kwarg) Parameters: ax: This parameter is an optional parameter and it contains Axes or list of Axes.
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:
cb=plt.colorbar()
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With