|
11 | 11 | End-users most likely won't need to directly use this module's API. |
12 | 12 | """ |
13 | 13 |
|
| 14 | +import functools |
14 | 15 | import logging |
15 | 16 |
|
16 | 17 | import numpy as np |
@@ -194,6 +195,17 @@ def get_subplotspec(self): |
194 | 195 | or getattr(self._orig_locator, "get_subplotspec", lambda: None)()) |
195 | 196 |
|
196 | 197 |
|
| 198 | +def _remove_cbar_axes(ax, cbar): |
| 199 | + """ |
| 200 | + Replacement remove method for a colorbar's axes, so that the colorbar is |
| 201 | + properly removed. |
| 202 | +
|
| 203 | + Note we define this at the module level to preserve pickling. A lambda or |
| 204 | + local def within the Colorbar.__init__ method will not work. |
| 205 | + """ |
| 206 | + cbar.remove() |
| 207 | + |
| 208 | + |
197 | 209 | @_docstring.interpd |
198 | 210 | class Colorbar: |
199 | 211 | r""" |
@@ -427,6 +439,14 @@ def __init__( |
427 | 439 | self._extend_cid2 = self.ax.callbacks.connect( |
428 | 440 | "ylim_changed", self._do_extends) |
429 | 441 |
|
| 442 | + # Ensure proper cleanup when `cbar.ax.remove()` is called. We ensure |
| 443 | + # this by overriding the Axes' remove method, so that `cbar.ax.remove()` |
| 444 | + # actually calls `cbar.remove()`. In turn, we store the original Axes' |
| 445 | + # remove method in `_ax_remove`, which `cbar.remove()` will eventually |
| 446 | + # call to clean up the Axes itself. |
| 447 | + self._ax_remove = self.ax._remove_method |
| 448 | + self.ax._remove_method = functools.partial(_remove_cbar_axes, cbar=self) |
| 449 | + |
430 | 450 | @property |
431 | 451 | def long_axis(self): |
432 | 452 | """Axis that has decorations (ticks, etc) on it.""" |
@@ -1032,7 +1052,7 @@ def remove(self): |
1032 | 1052 | if self.ax in a._colorbars: |
1033 | 1053 | a._colorbars.remove(self.ax) |
1034 | 1054 |
|
1035 | | - self.ax.remove() |
| 1055 | + self._ax_remove(self.ax) |
1036 | 1056 |
|
1037 | 1057 | self.mappable.callbacks.disconnect(self.mappable.colorbar_cid) |
1038 | 1058 | self.mappable.colorbar = None |
|
0 commit comments