File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1111 End-users most likely won't need to directly use this module's API.
1212"""
1313
14+ import functools
1415import logging
1516
1617import numpy as np
@@ -194,6 +195,14 @@ def get_subplotspec(self):
194195 or getattr (self ._orig_locator , "get_subplotspec" , lambda : None )())
195196
196197
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+ cbar .remove ()
204+
205+
197206@_docstring .interpd
198207class Colorbar :
199208 r"""
@@ -427,6 +436,10 @@ def __init__(
427436 self ._extend_cid2 = self .ax .callbacks .connect (
428437 "ylim_changed" , self ._do_extends )
429438
439+ # Override axes' remove method to properly remove the colorbar
440+ self ._ax_remove = self .ax ._remove_method
441+ self .ax ._remove_method = functools .partial (_remove_cbar_axes , cbar = self )
442+
430443 @property
431444 def long_axis (self ):
432445 """Axis that has decorations (ticks, etc) on it."""
@@ -1032,7 +1045,7 @@ def remove(self):
10321045 if self .ax in a ._colorbars :
10331046 a ._colorbars .remove (self .ax )
10341047
1035- self .ax . remove ( )
1048+ self ._ax_remove ( self . ax )
10361049
10371050 self .mappable .callbacks .disconnect (self .mappable .colorbar_cid )
10381051 self .mappable .colorbar = None
Original file line number Diff line number Diff line change 11import platform
2+ from unittest import mock
23
34import numpy as np
45import pytest
@@ -311,6 +312,18 @@ def test_remove_from_figure_cl():
311312 post_position .get_points ())
312313
313314
315+ def test_axes_remove ():
316+ """Removing the colorbar's axes should also remove the colorbar"""
317+ fig , ax = plt .subplots ()
318+ sc = ax .scatter ([1 , 2 ], [3 , 4 ])
319+ cb = fig .colorbar (sc )
320+
321+ with mock .patch .object (cb , 'remove' ) as mock_cb_remove :
322+ cb .ax .remove ()
323+
324+ mock_cb_remove .assert_called ()
325+
326+
314327def test_colorbarbase ():
315328 # smoke test from #3805
316329 ax = plt .gca ()
You can’t perform that action at this time.
0 commit comments