diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index 2262c3305bf5..a84c56d6b462 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -2248,12 +2248,37 @@ def _redo_transform_rel_fig(self, bbox=None): return # need to figure out *where* this subplotspec is. gs = self._subplotspec.get_gridspec() + subplot_params = gs.get_subplot_params(self) wr = np.asarray(gs.get_width_ratios()) hr = np.asarray(gs.get_height_ratios()) dx = wr[self._subplotspec.colspan].sum() / wr.sum() dy = hr[self._subplotspec.rowspan].sum() / hr.sum() x0 = wr[:self._subplotspec.colspan.start].sum() / wr.sum() y0 = 1 - hr[:self._subplotspec.rowspan.stop].sum() / hr.sum() + wspace = subplot_params.wspace + hspace = subplot_params.hspace + if not self._subplotspec.is_first_row(): + # add space to the top + avg_width = 1 / len(wr) + padding = (hspace * avg_width) * dy + dy -= padding + if not self._subplotspec.is_first_col(): + # add space to the left + avg_width = 1 / len(wr) + padding = (wspace * avg_width) * dx + dx -= padding + x0 += padding + if not self._subplotspec.is_last_row(): + # add space to the bottom + avg_width = 1 / len(wr) + padding = (hspace * avg_width) * dy + dy -= padding + y0 += padding + if not self._subplotspec.is_last_col(): + # add space to the right + avg_width = 1 / len(wr) + padding = (wspace * avg_width) * dx + dx -= padding if self.bbox_relative is None: self.bbox_relative = Bbox.from_bounds(x0, y0, dx, dy) else: diff --git a/lib/matplotlib/tests/baseline_images/test_figure/test_wspace_hspace_subfigure.png b/lib/matplotlib/tests/baseline_images/test_figure/test_wspace_hspace_subfigure.png new file mode 100644 index 000000000000..bccd0fc31589 Binary files /dev/null and b/lib/matplotlib/tests/baseline_images/test_figure/test_wspace_hspace_subfigure.png differ diff --git a/lib/matplotlib/tests/test_figure.py b/lib/matplotlib/tests/test_figure.py index d8b06003cd00..1ebecd69e222 100644 --- a/lib/matplotlib/tests/test_figure.py +++ b/lib/matplotlib/tests/test_figure.py @@ -892,6 +892,15 @@ def test_tightbbox_box_aspect(): ax2.set_box_aspect((2, 1, 1)) +@image_comparison(['test_wspace_hspace_subfigure.png'], + remove_text=True) +def test_wspace_hspace_subfigure(): + figs = plt.figure().subfigures(2, 2, hspace=0.2, wspace=0.2) + for fig, color in zip(figs.flat, 'cmyw'): + fig.set_facecolor(color) + fig.subplots().plot([1, 2]) + + @check_figures_equal(extensions=["svg", "pdf", "eps", "png"]) def test_animated_with_canvas_change(fig_test, fig_ref): ax_ref = fig_ref.subplots()