From d156691dcc7371b6ad5c231aee07844c7d7f2d2a Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Tue, 17 Nov 2020 20:51:46 +0100 Subject: [PATCH] Fix clabel() for backends without canvas.get_renderer() `tight_layout.get_renderer()` does the right dance to set up a renderer for any canvas. Perhaps it also should be moved somewhere more easily findable and it should be better disambiguated with `backend_bases._get_renderer()`, but that can be left for another time... --- lib/matplotlib/contour.py | 2 +- lib/matplotlib/tests/test_contour.py | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py index d3df90d73972..7aa597c91419 100644 --- a/lib/matplotlib/contour.py +++ b/lib/matplotlib/contour.py @@ -250,7 +250,7 @@ def get_label_width(self, lev, fmt, fsize): fig = self.axes.figure width = (text.Text(0, 0, lev, figure=fig, size=fsize, fontproperties=self.labelFontProps) - .get_window_extent(fig.canvas.get_renderer()).width) + .get_window_extent(mpl.tight_layout.get_renderer(fig)).width) width *= 72 / fig.dpi return width diff --git a/lib/matplotlib/tests/test_contour.py b/lib/matplotlib/tests/test_contour.py index 883431fe627a..58c15c9b34fa 100644 --- a/lib/matplotlib/tests/test_contour.py +++ b/lib/matplotlib/tests/test_contour.py @@ -392,3 +392,9 @@ def test_contour_linewidth( X = np.arange(4*3).reshape(4, 3) cs = ax.contour(X, linewidths=call_linewidths) assert cs.tlinewidths[0][0] == expected + + +@pytest.mark.backend("pdf") +def test_label_nonagg(): + # This should not crash even if the canvas doesn't have a get_renderer(). + plt.clabel(plt.contour([[1, 2], [3, 4]]))