From e78a3d149291561295a36806c0a2c62642c3f1af Mon Sep 17 00:00:00 2001 From: David Stansby Date: Sun, 28 Nov 2021 13:54:03 +0000 Subject: [PATCH] Backport PR #21751: FIX: manual colorbars and tight layout --- lib/matplotlib/colorbar.py | 2 ++ lib/matplotlib/tests/test_tightlayout.py | 13 +++++++++++++ lib/matplotlib/tight_layout.py | 13 +++++++------ 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index 15d6a4824dfa..7896ca69e1db 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -280,6 +280,8 @@ def get_subplotspec(self): # make tight_layout happy.. ss = getattr(self._cbar.ax, 'get_subplotspec', None) if ss is None: + if self._orig_locator is None: + return None ss = self._orig_locator.get_subplotspec() else: ss = ss() diff --git a/lib/matplotlib/tests/test_tightlayout.py b/lib/matplotlib/tests/test_tightlayout.py index 23d363b5083b..e9b01b160da1 100644 --- a/lib/matplotlib/tests/test_tightlayout.py +++ b/lib/matplotlib/tests/test_tightlayout.py @@ -329,3 +329,16 @@ def __init__(self, *args, **kwargs): monkeypatch.setattr(mpl.backend_bases.RendererBase, "__init__", __init__) fig, ax = plt.subplots() fig.tight_layout() + + +def test_manual_colorbar(): + # This should warn, but not raise + fig, axes = plt.subplots(1, 2) + pts = axes[1].scatter([0, 1], [0, 1], c=[1, 5]) + ax_rect = axes[1].get_position() + cax = fig.add_axes( + [ax_rect.x1 + 0.005, ax_rect.y0, 0.015, ax_rect.height] + ) + fig.colorbar(pts, cax=cax) + with pytest.warns(UserWarning, match="This figure includes Axes"): + fig.tight_layout() diff --git a/lib/matplotlib/tight_layout.py b/lib/matplotlib/tight_layout.py index 809b970915a9..ccd4b928af70 100644 --- a/lib/matplotlib/tight_layout.py +++ b/lib/matplotlib/tight_layout.py @@ -232,13 +232,14 @@ def get_subplotspec_list(axes_list, grid_spec=None): if hasattr(axes_or_locator, "get_subplotspec"): subplotspec = axes_or_locator.get_subplotspec() - subplotspec = subplotspec.get_topmost_subplotspec() - gs = subplotspec.get_gridspec() - if grid_spec is not None: - if gs != grid_spec: + if subplotspec is not None: + subplotspec = subplotspec.get_topmost_subplotspec() + gs = subplotspec.get_gridspec() + if grid_spec is not None: + if gs != grid_spec: + subplotspec = None + elif gs.locally_modified_subplot_params(): subplotspec = None - elif gs.locally_modified_subplot_params(): - subplotspec = None else: subplotspec = None