From 64fc6fbf26ffb5b1d98ccb99b66df686f617d900 Mon Sep 17 00:00:00 2001 From: David Stansby Date: Sun, 17 Oct 2021 11:33:19 +0100 Subject: [PATCH] Add a Figure._get_cachedRenderer() method --- lib/matplotlib/figure.py | 12 ++++++++---- lib/matplotlib/legend.py | 2 +- lib/matplotlib/tests/test_legend.py | 8 ++++++++ 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index aae1ef07a4ae..794017f50562 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -2376,6 +2376,13 @@ def axes(self): get_axes = axes.fget + def _get_cachedRenderer(self, error_if_none=True): + # Get the cached renderer, raising an error if it doesn't exist yet + if error_if_none and self._cachedRenderer is None: + raise RuntimeError("This code can only be used after an " + "initial draw which caches the renderer.") + return self._cachedRenderer + def _get_dpi(self): return self._dpi @@ -2829,10 +2836,7 @@ def draw_artist(self, a): This method can only be used after an initial draw of the figure, because that creates and caches the renderer needed here. """ - if self._cachedRenderer is None: - raise AttributeError("draw_artist can only be used after an " - "initial draw which caches the renderer") - a.draw(self._cachedRenderer) + a.draw(self._get_cachedRenderer()) def __getstate__(self): state = super().__getstate__() diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py index 2f83b323f4d4..0811202f48f9 100644 --- a/lib/matplotlib/legend.py +++ b/lib/matplotlib/legend.py @@ -881,7 +881,7 @@ def get_title(self): def get_window_extent(self, renderer=None): # docstring inherited if renderer is None: - renderer = self.figure._cachedRenderer + renderer = self.figure._get_cachedRenderer() return self._legend_box.get_window_extent(renderer=renderer) def get_tightbbox(self, renderer): diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py index 21c8ab748d9b..674a0424f523 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -880,3 +880,11 @@ def test_subfigure_legend(): ax.plot([0, 1], [0, 1], label="line") leg = subfig.legend() assert leg.figure is subfig + + +def test_no_renderer_error(): + leg = plt.legend() + with pytest.raises( + RuntimeError, + match='This code can only be used after an initial draw'): + leg.get_window_extent() pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy