从matplotlib中的图中删除颜色条
这应该很容易,但是我很难过.基本上,我在matplotlib中有一个子图,每次调用一个函数时,我都会绘制一个六边形图,但是每次调用该函数时,都会得到一个新的颜色条,所以我真正想做的就是更新颜色条.不幸的是,这似乎不起作用,因为通过subplot.hexbin重新创建了附加颜色栏的对象.
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)
我现在在这个烦人的地方,试图完全删除颜色条轴,然后重新创建它.不幸的是,当我删除颜色条轴时,子图轴不会回收空间,并且调用self.subplot.reset_position()并没有达到我的预期.
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)
有人有什么建议吗?
非常感谢! 亚当
好的,这是我的解决方案.不是很优雅,但也不是一个可怕的骇客.
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.