Skip to content

Commit 412a5a0

Browse files
authored
Merge pull request matplotlib#27360 from anntzer/cbngs
Fix removal of colorbars on nested subgridspecs.
2 parents 02489d4 + 7879189 commit 412a5a0

File tree

2 files changed

+14
-16
lines changed

2 files changed

+14
-16
lines changed

lib/matplotlib/colorbar.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1035,14 +1035,11 @@ def remove(self):
10351035
except AttributeError:
10361036
return
10371037
try:
1038-
gs = ax.get_subplotspec().get_gridspec()
1039-
subplotspec = gs.get_topmost_subplotspec()
1040-
except AttributeError:
1041-
# use_gridspec was False
1038+
subplotspec = self.ax.get_subplotspec().get_gridspec()._subplot_spec
1039+
except AttributeError: # use_gridspec was False
10421040
pos = ax.get_position(original=True)
10431041
ax._set_position(pos)
1044-
else:
1045-
# use_gridspec was True
1042+
else: # use_gridspec was True
10461043
ax.set_subplotspec(subplotspec)
10471044

10481045
def _process_values(self):

lib/matplotlib/tests/test_colorbar.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -279,13 +279,16 @@ def test_colorbar_single_scatter():
279279
plt.colorbar(cs)
280280

281281

282-
@pytest.mark.parametrize('use_gridspec', [False, True],
283-
ids=['no gridspec', 'with gridspec'])
284-
def test_remove_from_figure(use_gridspec):
285-
"""
286-
Test `remove` with the specified ``use_gridspec`` setting
287-
"""
288-
fig, ax = plt.subplots()
282+
@pytest.mark.parametrize('use_gridspec', [True, False])
283+
@pytest.mark.parametrize('nested_gridspecs', [True, False])
284+
def test_remove_from_figure(nested_gridspecs, use_gridspec):
285+
"""Test `remove` with the specified ``use_gridspec`` setting."""
286+
fig = plt.figure()
287+
if nested_gridspecs:
288+
gs = fig.add_gridspec(2, 2)[1, 1].subgridspec(2, 2)
289+
ax = fig.add_subplot(gs[1, 1])
290+
else:
291+
ax = fig.add_subplot()
289292
sc = ax.scatter([1, 2], [3, 4])
290293
sc.set_array(np.array([5, 6]))
291294
pre_position = ax.get_position()
@@ -298,9 +301,7 @@ def test_remove_from_figure(use_gridspec):
298301

299302

300303
def test_remove_from_figure_cl():
301-
"""
302-
Test `remove` with constrained_layout
303-
"""
304+
"""Test `remove` with constrained_layout."""
304305
fig, ax = plt.subplots(constrained_layout=True)
305306
sc = ax.scatter([1, 2], [3, 4])
306307
sc.set_array(np.array([5, 6]))

0 commit comments

Comments
 (0)