diff --git a/galleries/users_explain/axes/colorbar_placement.py b/galleries/users_explain/axes/colorbar_placement.py index 8dbc2a356cb1..919600b070f3 100644 --- a/galleries/users_explain/axes/colorbar_placement.py +++ b/galleries/users_explain/axes/colorbar_placement.py @@ -53,7 +53,7 @@ fig, axs = plt.subplots(2, 1, figsize=(4, 5), sharex=True) X = np.random.randn(20, 20) axs[0].plot(np.sum(X, axis=0)) -axs[1].pcolormesh(X) +pcm = axs[1].pcolormesh(X) fig.colorbar(pcm, ax=axs[1], shrink=0.6) # %% @@ -63,7 +63,7 @@ fig, axs = plt.subplots(2, 1, figsize=(4, 5), sharex=True, layout='constrained') axs[0].plot(np.sum(X, axis=0)) -axs[1].pcolormesh(X) +pcm = axs[1].pcolormesh(X) fig.colorbar(pcm, ax=axs[1], shrink=0.6) # %% diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index 11b42b1e1ac7..dd76c932b01e 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -1242,6 +1242,19 @@ def colorbar( fig.sca(current_ax) cax.grid(visible=False, which='both', axis='both') + if hasattr(mappable, "figure") and mappable.figure is not None: + # Get top level artists + mappable_host_fig = mappable.figure + if isinstance(mappable_host_fig, mpl.figure.SubFigure): + mappable_host_fig = mappable_host_fig.figure + # Warn in case of mismatch + if mappable_host_fig is not self.figure: + _api.warn_external( + f'Adding colorbar to a different Figure ' + f'{repr(mappable.figure)} than ' + f'{repr(self.figure)} which ' + f'fig.colorbar is called on.') + NON_COLORBAR_KEYS = [ # remove kws that cannot be passed to Colorbar 'fraction', 'pad', 'shrink', 'aspect', 'anchor', 'panchor'] cb = cbar.Colorbar(cax, mappable, **{ diff --git a/lib/matplotlib/tests/test_colorbar.py b/lib/matplotlib/tests/test_colorbar.py index 509d08dae183..4566ce449aac 100644 --- a/lib/matplotlib/tests/test_colorbar.py +++ b/lib/matplotlib/tests/test_colorbar.py @@ -1228,7 +1228,8 @@ def test_colorbar_wrong_figure(): im = fig_cl.add_subplot().imshow([[0, 1]]) # Make sure this doesn't try to setup a gridspec-controlled colorbar on fig_cl, # which would crash CL. - fig_tl.colorbar(im) + with pytest.warns(UserWarning, match="different Figure"): + fig_tl.colorbar(im) fig_tl.draw_without_rendering() fig_cl.draw_without_rendering() diff --git a/lib/matplotlib/tests/test_figure.py b/lib/matplotlib/tests/test_figure.py index 99b2602bc4a7..0e1706f37b59 100644 --- a/lib/matplotlib/tests/test_figure.py +++ b/lib/matplotlib/tests/test_figure.py @@ -1358,7 +1358,6 @@ def test_subfigure_double(): ax.set_xlabel('x-label', fontsize=fontsize) ax.set_ylabel('y-label', fontsize=fontsize) ax.set_title('Title', fontsize=fontsize) - subfigsnest[0].colorbar(pc, ax=axsnest0) subfigsnest[1].suptitle('subfigsnest[1]') @@ -1665,3 +1664,39 @@ def test_not_visible_figure(): fig.savefig(buf, format='svg') buf.seek(0) assert '