From f1e57545d1de0d56896a9f5fcad475b718b264cd Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Thu, 23 Mar 2023 20:13:55 -0400 Subject: [PATCH 1/3] FIX: skip Axes not in subplot layouts As of mpl 3.7 all Axes now report as being instances of Subplots, however ax.get_subplotspec() may now return None if the Axes is not actually in gridspec. --- pandas/plotting/_matplotlib/core.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 49b92e0984713..dd6b419c9a56b 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -1112,7 +1112,9 @@ def _get_subplots(self): from matplotlib.axes import Subplot return [ - ax for ax in self.axes[0].get_figure().get_axes() if isinstance(ax, Subplot) + ax + for ax in self.axes[0].get_figure().get_axes() + if (isinstance(ax, Subplot) and ax.get_subplotspec() is not None) ] def _get_axes_layout(self) -> tuple[int, int]: From 3e66bcb4985540b97306523a6827b6951b0e436c Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Thu, 23 Mar 2023 20:15:43 -0400 Subject: [PATCH 2/3] MNT: avoid unneeded indirection The MPLPlot instance already holds a reference to the Figure, use that instead of walking up from the first Axes. --- pandas/plotting/_matplotlib/core.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index dd6b419c9a56b..54bd1c843da79 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -1113,7 +1113,7 @@ def _get_subplots(self): return [ ax - for ax in self.axes[0].get_figure().get_axes() + for ax in self.fig.get_axes() if (isinstance(ax, Subplot) and ax.get_subplotspec() is not None) ] From 67113f9560040d42e3b7b2fd099f0671537e241e Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Thu, 23 Mar 2023 20:20:38 -0400 Subject: [PATCH 3/3] TST: add test of trying to layout a colorbar --- pandas/tests/plotting/test_common.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/pandas/tests/plotting/test_common.py b/pandas/tests/plotting/test_common.py index d4624cfc74872..faf8278675566 100644 --- a/pandas/tests/plotting/test_common.py +++ b/pandas/tests/plotting/test_common.py @@ -40,3 +40,22 @@ def test__gen_two_subplots_with_ax(self): subplot_geometry = list(axes[0].get_subplotspec().get_geometry()[:-1]) subplot_geometry[-1] += 1 assert subplot_geometry == [2, 1, 2] + + def test_colorbar_layout(self): + fig = self.plt.figure() + + axes = fig.subplot_mosaic( + """ + AB + CC + """ + ) + + x = [1, 2, 3] + y = [1, 2, 3] + + cs0 = axes["A"].scatter(x, y) + axes["B"].scatter(x, y) + + fig.colorbar(cs0, ax=[axes["A"], axes["B"]], location="right") + DataFrame(x).plot(ax=axes["C"])