Skip to content

Commit cbf807e

Browse files
committed
MNT: make renderer always optional
1 parent a436253 commit cbf807e

File tree

21 files changed

+127
-81
lines changed

21 files changed

+127
-81
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
No need to specify renderer for get_tightbbox and get_window_extent
2+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3+
4+
The ``get_tightbbox`` and `~.Artist.get_window_extent` methods
5+
no longer require the *renderer* kwarg, saving users from having to
6+
querry it from ``fig.canvas.get_renderer``. Currently, all Artists are
7+
aware of their parent figure (``artist.figure``), and if the *renderer*
8+
kwarg is not supplied these methods first check if there is a cached renderer
9+
from a previous draw and use that. If there is no cahched renderer, then
10+
the methods will use ``fig.canvas.get_renderer()`` as a fallback.

lib/matplotlib/_constrained_layout.py

Lines changed: 20 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
import numpy as np
1919

2020
from matplotlib import _api, artist as martist
21-
from matplotlib._tight_layout import get_renderer
2221
import matplotlib.transforms as mtransforms
2322
import matplotlib._layoutgrid as mlayoutgrid
2423

@@ -74,8 +73,6 @@ def do_constrained_layout(fig, h_pad, w_pad,
7473
fig : Figure
7574
``Figure`` instance to do the layout in.
7675
77-
renderer : Renderer
78-
Renderer to use.
7976
8077
h_pad, w_pad : float
8178
Padding around the axes elements in figure-normalized units.
@@ -92,7 +89,6 @@ def do_constrained_layout(fig, h_pad, w_pad,
9289
layoutgrid : private debugging structure
9390
"""
9491

95-
renderer = get_renderer(fig)
9692
# make layoutgrid tree...
9793
layoutgrids = make_layoutgrids(fig, None)
9894
if not layoutgrids['hasgrids']:
@@ -109,9 +105,9 @@ def do_constrained_layout(fig, h_pad, w_pad,
109105

110106
# make margins for all the axes and subfigures in the
111107
# figure. Add margins for colorbars...
112-
make_layout_margins(layoutgrids, fig, renderer, h_pad=h_pad,
108+
make_layout_margins(layoutgrids, fig, h_pad=h_pad,
113109
w_pad=w_pad, hspace=hspace, wspace=wspace)
114-
make_margin_suptitles(layoutgrids, fig, renderer, h_pad=h_pad,
110+
make_margin_suptitles(layoutgrids, fig, h_pad=h_pad,
115111
w_pad=w_pad)
116112

117113
# if a layout is such that a columns (or rows) margin has no
@@ -123,7 +119,7 @@ def do_constrained_layout(fig, h_pad, w_pad,
123119
layoutgrids[fig].update_variables()
124120

125121
if check_no_collapsed_axes(layoutgrids, fig):
126-
reposition_axes(layoutgrids, fig, renderer, h_pad=h_pad,
122+
reposition_axes(layoutgrids, fig, h_pad=h_pad,
127123
w_pad=w_pad, hspace=hspace, wspace=wspace)
128124
else:
129125
_api.warn_external('constrained_layout not applied because '
@@ -283,7 +279,7 @@ def get_margin_from_padding(obj, *, w_pad=0, h_pad=0,
283279
return margin
284280

285281

286-
def make_layout_margins(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0,
282+
def make_layout_margins(layoutgrids, fig, *, w_pad=0, h_pad=0,
287283
hspace=0, wspace=0):
288284
"""
289285
For each axes, make a margin between the *pos* layoutbox and the
@@ -294,7 +290,7 @@ def make_layout_margins(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0,
294290
"""
295291
for sfig in fig.subfigs: # recursively make child panel margins
296292
ss = sfig._subplotspec
297-
make_layout_margins(layoutgrids, sfig, renderer,
293+
make_layout_margins(layoutgrids, sfig,
298294
w_pad=w_pad, h_pad=h_pad,
299295
hspace=hspace, wspace=wspace)
300296

@@ -314,7 +310,7 @@ def make_layout_margins(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0,
314310

315311
margin = get_margin_from_padding(ax, w_pad=w_pad, h_pad=h_pad,
316312
hspace=hspace, wspace=wspace)
317-
pos, bbox = get_pos_and_bbox(ax, renderer)
313+
pos, bbox = get_pos_and_bbox(ax)
318314
# the margin is the distance between the bounding box of the axes
319315
# and its position (plus the padding from above)
320316
margin['left'] += pos.x0 - bbox.x0
@@ -331,7 +327,7 @@ def make_layout_margins(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0,
331327
# colorbars can be child of more than one subplot spec:
332328
cbp_rspan, cbp_cspan = get_cb_parent_spans(cbax)
333329
loc = cbax._colorbar_info['location']
334-
cbpos, cbbbox = get_pos_and_bbox(cbax, renderer)
330+
cbpos, cbbbox = get_pos_and_bbox(cbax)
335331
if loc == 'right':
336332
if cbp_cspan.stop == ss.colspan.stop:
337333
# only increase if the colorbar is on the right edge
@@ -367,7 +363,7 @@ def make_layout_margins(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0,
367363
layoutgrids[gs].edit_outer_margin_mins(margin, ss)
368364

369365

370-
def make_margin_suptitles(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0):
366+
def make_margin_suptitles(layoutgrids, fig, *, w_pad=0, h_pad=0):
371367
# Figure out how large the suptitle is and make the
372368
# top level figure margin larger.
373369

@@ -380,29 +376,29 @@ def make_margin_suptitles(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0):
380376
w_pad_local = padbox.width
381377

382378
for sfig in fig.subfigs:
383-
make_margin_suptitles(layoutgrids, sfig, renderer,
379+
make_margin_suptitles(layoutgrids, sfig,
384380
w_pad=w_pad, h_pad=h_pad)
385381

386382
if fig._suptitle is not None and fig._suptitle.get_in_layout():
387383
p = fig._suptitle.get_position()
388384
if getattr(fig._suptitle, '_autopos', False):
389385
fig._suptitle.set_position((p[0], 1 - h_pad_local))
390-
bbox = inv_trans_fig(fig._suptitle.get_tightbbox(renderer))
386+
bbox = inv_trans_fig(fig._suptitle.get_tightbbox())
391387
layoutgrids[fig].edit_margin_min('top', bbox.height + 2 * h_pad)
392388

393389
if fig._supxlabel is not None and fig._supxlabel.get_in_layout():
394390
p = fig._supxlabel.get_position()
395391
if getattr(fig._supxlabel, '_autopos', False):
396392
fig._supxlabel.set_position((p[0], h_pad_local))
397-
bbox = inv_trans_fig(fig._supxlabel.get_tightbbox(renderer))
393+
bbox = inv_trans_fig(fig._supxlabel.get_tightbbox())
398394
layoutgrids[fig].edit_margin_min('bottom',
399395
bbox.height + 2 * h_pad)
400396

401397
if fig._supylabel is not None and fig._supylabel.get_in_layout():
402398
p = fig._supylabel.get_position()
403399
if getattr(fig._supylabel, '_autopos', False):
404400
fig._supylabel.set_position((w_pad_local, p[1]))
405-
bbox = inv_trans_fig(fig._supylabel.get_tightbbox(renderer))
401+
bbox = inv_trans_fig(fig._supylabel.get_tightbbox())
406402
layoutgrids[fig].edit_margin_min('left', bbox.width + 2 * w_pad)
407403

408404

@@ -523,14 +519,14 @@ def get_cb_parent_spans(cbax):
523519
return rowspan, colspan
524520

525521

526-
def get_pos_and_bbox(ax, renderer):
522+
def get_pos_and_bbox(ax):
527523
"""
528524
Get the position and the bbox for the axes.
529525
530526
Parameters
531527
----------
532528
ax
533-
renderer
529+
534530
535531
Returns
536532
-------
@@ -543,15 +539,15 @@ def get_pos_and_bbox(ax, renderer):
543539
pos = ax.get_position(original=True)
544540
# pos is in panel co-ords, but we need in figure for the layout
545541
pos = pos.transformed(fig.transSubfigure - fig.transFigure)
546-
tightbbox = martist._get_tightbbox_for_layout_only(ax, renderer)
542+
tightbbox = martist._get_tightbbox_for_layout_only(ax)
547543
if tightbbox is None:
548544
bbox = pos
549545
else:
550546
bbox = tightbbox.transformed(fig.transFigure.inverted())
551547
return pos, bbox
552548

553549

554-
def reposition_axes(layoutgrids, fig, renderer, *,
550+
def reposition_axes(layoutgrids, fig, *,
555551
w_pad=0, h_pad=0, hspace=0, wspace=0):
556552
"""
557553
Reposition all the axes based on the new inner bounding box.
@@ -561,7 +557,7 @@ def reposition_axes(layoutgrids, fig, renderer, *,
561557
bbox = layoutgrids[sfig].get_outer_bbox()
562558
sfig._redo_transform_rel_fig(
563559
bbox=bbox.transformed(trans_fig_to_subfig))
564-
reposition_axes(layoutgrids, sfig, renderer,
560+
reposition_axes(layoutgrids, sfig,
565561
w_pad=w_pad, h_pad=h_pad,
566562
wspace=wspace, hspace=hspace)
567563

@@ -589,11 +585,11 @@ def reposition_axes(layoutgrids, fig, renderer, *,
589585
offset = {'left': 0, 'right': 0, 'bottom': 0, 'top': 0}
590586
for nn, cbax in enumerate(ax._colorbars[::-1]):
591587
if ax == cbax._colorbar_info['parents'][0]:
592-
reposition_colorbar(layoutgrids, cbax, renderer,
588+
reposition_colorbar(layoutgrids, cbax,
593589
offset=offset)
594590

595591

596-
def reposition_colorbar(layoutgrids, cbax, renderer, *, offset=None):
592+
def reposition_colorbar(layoutgrids, cbax, *, offset=None):
597593
"""
598594
Place the colorbar in its new place.
599595
@@ -602,7 +598,6 @@ def reposition_colorbar(layoutgrids, cbax, renderer, *, offset=None):
602598
cbax : Axes
603599
Axes for the colorbar
604600
605-
renderer :
606601
w_pad, h_pad : float
607602
width and height padding (in fraction of figure)
608603
hspace, wspace : float
@@ -629,7 +624,7 @@ def reposition_colorbar(layoutgrids, cbax, renderer, *, offset=None):
629624
aspect = cbax._colorbar_info['aspect']
630625
shrink = cbax._colorbar_info['shrink']
631626

632-
cbpos, cbbbox = get_pos_and_bbox(cbax, renderer)
627+
cbpos, cbbbox = get_pos_and_bbox(cbax)
633628

634629
# Colorbar gets put at extreme edge of outer bbox of the subplotspec
635630
# It needs to be moved in by: 1) a pad 2) its "margin" 3) by

lib/matplotlib/_tight_layout.py

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -199,15 +199,7 @@ def auto_adjust_subplotpars(
199199

200200

201201
def get_renderer(fig):
202-
if fig._cachedRenderer:
203-
return fig._cachedRenderer
204-
else:
205-
canvas = fig.canvas
206-
if canvas and hasattr(canvas, "get_renderer"):
207-
return canvas.get_renderer()
208-
else:
209-
from . import backend_bases
210-
return backend_bases._get_renderer(fig)
202+
fig._get_cached_renderer()
211203

212204

213205
def get_subplotspec_list(axes_list, grid_spec=None):
@@ -244,7 +236,7 @@ def get_subplotspec_list(axes_list, grid_spec=None):
244236
return subplotspec_list
245237

246238

247-
def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer,
239+
def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer=None,
248240
pad=1.08, h_pad=None, w_pad=None, rect=None):
249241
"""
250242
Return subplot parameters for tight-layouted-figure with specified padding.

lib/matplotlib/artist.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ def stale(self, val):
298298
if val and self.stale_callback is not None:
299299
self.stale_callback(self, val)
300300

301-
def get_window_extent(self, renderer):
301+
def get_window_extent(self, renderer=None):
302302
"""
303303
Get the artist's bounding box in display space.
304304
@@ -318,7 +318,7 @@ def get_window_extent(self, renderer):
318318
"""
319319
return Bbox([[0, 0], [0, 0]])
320320

321-
def get_tightbbox(self, renderer):
321+
def get_tightbbox(self, renderer=None):
322322
"""
323323
Like `.Artist.get_window_extent`, but includes any clipping.
324324

lib/matplotlib/axes/_base.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4433,7 +4433,7 @@ def get_default_bbox_extra_artists(self):
44334433
return [a for a in artists if a.get_visible() and a.get_in_layout()
44344434
and (isinstance(a, noclip) or not a._fully_clipped_to_axes())]
44354435

4436-
def get_tightbbox(self, renderer, call_axes_locator=True,
4436+
def get_tightbbox(self, renderer=None, call_axes_locator=True,
44374437
bbox_extra_artists=None, *, for_layout_only=False):
44384438
"""
44394439
Return the tight bounding box of the Axes, including axis and their
@@ -4477,6 +4477,8 @@ def get_tightbbox(self, renderer, call_axes_locator=True,
44774477
"""
44784478

44794479
bb = []
4480+
if renderer is None:
4481+
renderer = self.figure._get_cached_renderer()
44804482

44814483
if not self.get_visible():
44824484
return None

lib/matplotlib/axis.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1200,14 +1200,16 @@ def _update_ticks(self):
12001200

12011201
return ticks_to_draw
12021202

1203-
def _get_ticklabel_bboxes(self, ticks, renderer):
1203+
def _get_ticklabel_bboxes(self, ticks, renderer=None):
12041204
"""Return lists of bboxes for ticks' label1's and label2's."""
1205+
if renderer is None:
1206+
renderer = self.figure._get_cached_renderer()
12051207
return ([tick.label1.get_window_extent(renderer)
12061208
for tick in ticks if tick.label1.get_visible()],
12071209
[tick.label2.get_window_extent(renderer)
12081210
for tick in ticks if tick.label2.get_visible()])
12091211

1210-
def get_tightbbox(self, renderer, *, for_layout_only=False):
1212+
def get_tightbbox(self, renderer=None, *, for_layout_only=False):
12111213
"""
12121214
Return a bounding box that encloses the axis. It only accounts
12131215
tick labels, axis label, and offsetText.
@@ -1219,7 +1221,8 @@ def get_tightbbox(self, renderer, *, for_layout_only=False):
12191221
"""
12201222
if not self.get_visible():
12211223
return
1222-
1224+
if renderer is None:
1225+
renderer = self.figure._get_cached_renderer()
12231226
ticks_to_draw = self._update_ticks()
12241227

12251228
self._update_label_position(renderer)

lib/matplotlib/collections.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ def get_datalim(self, transData):
304304
return bbox
305305
return transforms.Bbox.null()
306306

307-
def get_window_extent(self, renderer):
307+
def get_window_extent(self, renderer=None):
308308
# TODO: check to ensure that this does not fail for
309309
# cases other than scatter plot legend
310310
return self.get_datalim(transforms.IdentityTransform())

lib/matplotlib/figure.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1619,7 +1619,7 @@ def get_default_bbox_extra_artists(self):
16191619
bbox_artists.extend(ax.get_default_bbox_extra_artists())
16201620
return bbox_artists
16211621

1622-
def get_tightbbox(self, renderer, bbox_extra_artists=None):
1622+
def get_tightbbox(self, renderer=None, bbox_extra_artists=None):
16231623
"""
16241624
Return a (tight) bounding box of the figure *in inches*.
16251625
@@ -1646,6 +1646,9 @@ def get_tightbbox(self, renderer, bbox_extra_artists=None):
16461646
containing the bounding box (in figure inches).
16471647
"""
16481648

1649+
if renderer is None:
1650+
renderer = self.figure._get_cached_renderer()
1651+
16491652
bb = []
16501653
if bbox_extra_artists is None:
16511654
artists = self.get_default_bbox_extra_artists()
@@ -2055,6 +2058,9 @@ def dpi(self):
20552058
def dpi(self, value):
20562059
self._parent.dpi = value
20572060

2061+
def _get_cached_renderer(self):
2062+
return self._parent._get_cached_renderer()
2063+
20582064
def _redo_transform_rel_fig(self, bbox=None):
20592065
"""
20602066
Make the transSubfigure bbox relative to Figure transform.
@@ -2482,6 +2488,14 @@ def axes(self):
24822488

24832489
get_axes = axes.fget
24842490

2491+
def _get_cached_renderer(self):
2492+
if self._cachedRenderer is not None:
2493+
return self._cachedRenderer
2494+
elif hasattr(self.canvas, 'get_renderer'):
2495+
return self.canvas.get_renderer()
2496+
else:
2497+
return _get_renderer(self)
2498+
24852499
def _get_dpi(self):
24862500
return self._dpi
24872501

@@ -2630,7 +2644,7 @@ def get_constrained_layout_pads(self, relative=False):
26302644
hspace = info['hspace']
26312645

26322646
if relative and (w_pad is not None or h_pad is not None):
2633-
renderer = _get_renderer(self)
2647+
renderer = self._get_cached_renderer()
26342648
dpi = renderer.dpi
26352649
w_pad = w_pad * dpi / renderer.width
26362650
h_pad = h_pad * dpi / renderer.height

lib/matplotlib/image.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1425,7 +1425,7 @@ def __init__(self, bbox,
14251425

14261426
def get_window_extent(self, renderer=None):
14271427
if renderer is None:
1428-
renderer = self.get_figure()._cachedRenderer
1428+
renderer = self.get_figure()._get_cached_renderer()
14291429

14301430
if isinstance(self.bbox, BboxBase):
14311431
return self.bbox

lib/matplotlib/layout_engine.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,6 @@
2222
from matplotlib._constrained_layout import do_constrained_layout
2323
from matplotlib._tight_layout import (get_subplotspec_list,
2424
get_tight_layout_figure)
25-
# from matplotlib.backend_bases import _get_renderer
26-
from matplotlib._tight_layout import get_renderer
2725

2826

2927
class LayoutEngine:
@@ -154,7 +152,7 @@ def execute(self, fig):
154152
_api.warn_external("This figure includes Axes that are not "
155153
"compatible with tight_layout, so results "
156154
"might be incorrect.")
157-
renderer = get_renderer(fig)
155+
renderer = fig._get_cached_renderer()
158156
with getattr(renderer, "_draw_disabled", nullcontext)():
159157
kwargs = get_tight_layout_figure(
160158
fig, fig.axes, subplotspec_list, renderer,

0 commit comments

Comments
 (0)