@@ -1528,6 +1528,27 @@ def __init__(self, name, canvas, key, x=0, y=0, guiEvent=None):
15281528 self .key = key
15291529
15301530
1531+ def _get_renderer (figure , print_method ):
1532+ """
1533+ Get the renderer that would be used to save a `~.Figure`, and cache it on
1534+ the figure.
1535+ """
1536+ # This is implemented by triggering a draw, then immediately jumping out of
1537+ # Figure.draw() by raising an exception.
1538+
1539+ class Done (Exception ):
1540+ pass
1541+
1542+ def _draw (renderer ): raise Done (renderer )
1543+
1544+ with cbook ._setattr_cm (figure , draw = _draw ):
1545+ try :
1546+ print_method (io .BytesIO ())
1547+ except Done as exc :
1548+ figure ._cachedRenderer , = exc .args
1549+ return figure ._cachedRenderer
1550+
1551+
15311552class FigureCanvasBase (object ):
15321553 """
15331554 The canvas the figure renders into.
@@ -2038,20 +2059,11 @@ def print_figure(self, filename, dpi=None, facecolor=None, edgecolor=None,
20382059 bbox_inches = rcParams ['savefig.bbox' ]
20392060
20402061 if bbox_inches :
2041- # call adjust_bbox to save only the given area
20422062 if bbox_inches == "tight" :
2043- # When bbox_inches == "tight", it saves the figure twice.
2044- # The first save command (to a BytesIO) is just to estimate
2045- # the bounding box of the figure.
2046- result = print_method (
2047- io .BytesIO (),
2048- dpi = dpi ,
2049- facecolor = facecolor ,
2050- edgecolor = edgecolor ,
2051- orientation = orientation ,
2052- dryrun = True ,
2053- ** kwargs )
2054- renderer = self .figure ._cachedRenderer
2063+ renderer = _get_renderer (
2064+ self .figure ,
2065+ functools .partial (
2066+ print_method , dpi = dpi , orientation = orientation ))
20552067 bbox_artists = kwargs .pop ("bbox_extra_artists" , None )
20562068 bbox_inches = self .figure .get_tightbbox (renderer ,
20572069 bbox_extra_artists = bbox_artists )
@@ -2061,6 +2073,7 @@ def print_figure(self, filename, dpi=None, facecolor=None, edgecolor=None,
20612073
20622074 bbox_inches = bbox_inches .padded (pad )
20632075
2076+ # call adjust_bbox to save only the given area
20642077 restore_bbox = tight_bbox .adjust_bbox (self .figure , bbox_inches ,
20652078 canvas .fixed_dpi )
20662079
0 commit comments