Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 25a54a4

Browse files
authored
Merge pull request #21751 from jklymak/fix-manual-colorbar-tight
FIX: manual colorbars and tight layout
2 parents 28a5f6d + 98cd347 commit 25a54a4

File tree

3 files changed

+22
-6
lines changed

3 files changed

+22
-6
lines changed

lib/matplotlib/colorbar.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,8 @@ def get_subplotspec(self):
280280
# make tight_layout happy..
281281
ss = getattr(self._cbar.ax, 'get_subplotspec', None)
282282
if ss is None:
283+
if self._orig_locator is None:
284+
return None
283285
ss = self._orig_locator.get_subplotspec()
284286
else:
285287
ss = ss()

lib/matplotlib/tests/test_tightlayout.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,3 +329,16 @@ def __init__(self, *args, **kwargs):
329329
monkeypatch.setattr(mpl.backend_bases.RendererBase, "__init__", __init__)
330330
fig, ax = plt.subplots()
331331
fig.tight_layout()
332+
333+
334+
def test_manual_colorbar():
335+
# This should warn, but not raise
336+
fig, axes = plt.subplots(1, 2)
337+
pts = axes[1].scatter([0, 1], [0, 1], c=[1, 5])
338+
ax_rect = axes[1].get_position()
339+
cax = fig.add_axes(
340+
[ax_rect.x1 + 0.005, ax_rect.y0, 0.015, ax_rect.height]
341+
)
342+
fig.colorbar(pts, cax=cax)
343+
with pytest.warns(UserWarning, match="This figure includes Axes"):
344+
fig.tight_layout()

lib/matplotlib/tight_layout.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -228,13 +228,14 @@ def get_subplotspec_list(axes_list, grid_spec=None):
228228

229229
if hasattr(axes_or_locator, "get_subplotspec"):
230230
subplotspec = axes_or_locator.get_subplotspec()
231-
subplotspec = subplotspec.get_topmost_subplotspec()
232-
gs = subplotspec.get_gridspec()
233-
if grid_spec is not None:
234-
if gs != grid_spec:
231+
if subplotspec is not None:
232+
subplotspec = subplotspec.get_topmost_subplotspec()
233+
gs = subplotspec.get_gridspec()
234+
if grid_spec is not None:
235+
if gs != grid_spec:
236+
subplotspec = None
237+
elif gs.locally_modified_subplot_params():
235238
subplotspec = None
236-
elif gs.locally_modified_subplot_params():
237-
subplotspec = None
238239
else:
239240
subplotspec = None
240241

0 commit comments

Comments
 (0)