Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/matplotlib/colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -992,6 +992,12 @@ def remove(self):
If the colorbar was created with ``use_gridspec=True`` the previous
gridspec is restored.
"""
if hasattr(self.ax, '_colorbar_info'):
parents = self.ax._colorbar_info['parents']
for a in parents:
if self.ax in a._colorbars:
a._colorbars.remove(self.ax)

self.ax.remove()

self.mappable.callbacks.disconnect(self.mappable.colorbar_cid)
Expand Down
19 changes: 18 additions & 1 deletion lib/matplotlib/tests/test_colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ def test_colorbar_single_scatter():
ids=['no gridspec', 'with gridspec'])
def test_remove_from_figure(use_gridspec):
"""
Test `remove_from_figure` with the specified ``use_gridspec`` setting
Test `remove` with the specified ``use_gridspec`` setting
"""
fig, ax = plt.subplots()
sc = ax.scatter([1, 2], [3, 4], cmap="spring")
Expand All @@ -235,6 +235,23 @@ def test_remove_from_figure(use_gridspec):
assert (pre_position.get_points() == post_position.get_points()).all()


def test_remove_from_figure_cl():
"""
Test `remove` with constrained_layout
"""
fig, ax = plt.subplots(constrained_layout=True)
sc = ax.scatter([1, 2], [3, 4], cmap="spring")
sc.set_array(np.array([5, 6]))
fig.draw_without_rendering()
pre_position = ax.get_position()
cb = fig.colorbar(sc)
cb.remove()
fig.draw_without_rendering()
post_position = ax.get_position()
np.testing.assert_allclose(pre_position.get_points(),
post_position.get_points())

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possibly add an assert that cb.ax isn't in the ax._colorbars list since that is the addition you're adding above?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My understanding is that we don't usually check private attributes?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If cb.ax is still in ax._colorbars this test will raise with the AttributeError: 'NoneType' object has no attribute 'transSubfigure' of the original issue. Thats what this test checks, I'm not convinced we need to test the implementation.


def test_colorbarbase():
# smoke test from #3805
ax = plt.gca()
Expand Down