Skip to content

Commit a9b8b6e

Browse files
QuLogicmeeseeksmachine
authored andcommitted
Backport PR #16734: Disable draw_foo methods on renderer used to estimate tight extents.
1 parent a4bb9d3 commit a9b8b6e

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

lib/matplotlib/backend_bases.py

+16-4
Original file line numberDiff line numberDiff line change
@@ -1516,10 +1516,15 @@ def __init__(self, name, canvas, key, x=0, y=0, guiEvent=None):
15161516
self.key = key
15171517

15181518

1519-
def _get_renderer(figure, print_method):
1519+
def _get_renderer(figure, print_method, *, draw_disabled=False):
15201520
"""
15211521
Get the renderer that would be used to save a `~.Figure`, and cache it on
15221522
the figure.
1523+
1524+
If *draw_disabled* is True, additionally replace draw_foo methods on
1525+
*renderer* by no-ops. This is used by the tight-bbox-saving renderer,
1526+
which needs to walk through the artist tree to compute the tight-bbox, but
1527+
for which the output file may be closed early.
15231528
"""
15241529
# This is implemented by triggering a draw, then immediately jumping out of
15251530
# Figure.draw() by raising an exception.
@@ -1533,8 +1538,14 @@ def _draw(renderer): raise Done(renderer)
15331538
try:
15341539
print_method(io.BytesIO())
15351540
except Done as exc:
1536-
figure._cachedRenderer, = exc.args
1537-
return figure._cachedRenderer
1541+
renderer, = figure._cachedRenderer, = exc.args
1542+
1543+
if draw_disabled:
1544+
for meth_name in dir(RendererBase):
1545+
if meth_name.startswith("draw_"):
1546+
setattr(renderer, meth_name, lambda *args, **kwargs: None)
1547+
1548+
return renderer
15381549

15391550

15401551
def _is_non_interactive_terminal_ipython(ip):
@@ -2063,7 +2074,8 @@ def print_figure(self, filename, dpi=None, facecolor=None, edgecolor=None,
20632074
renderer = _get_renderer(
20642075
self.figure,
20652076
functools.partial(
2066-
print_method, dpi=dpi, orientation=orientation))
2077+
print_method, dpi=dpi, orientation=orientation),
2078+
draw_disabled=True)
20672079
self.figure.draw(renderer)
20682080
bbox_artists = kwargs.pop("bbox_extra_artists", None)
20692081
bbox_inches = self.figure.get_tightbbox(renderer,

lib/matplotlib/tests/test_backend_pgf.py

+8
Original file line numberDiff line numberDiff line change
@@ -282,3 +282,11 @@ def test_tex_restart_after_error():
282282
fig = plt.figure() # start from scratch
283283
fig.suptitle(r"this is ok")
284284
fig.savefig(BytesIO(), format="pgf")
285+
286+
287+
@needs_xelatex
288+
def test_bbox_inches_tight(tmpdir):
289+
fig, ax = plt.subplots()
290+
ax.imshow([[0, 1], [2, 3]])
291+
fig.savefig(os.path.join(tmpdir, "test.pdf"), backend="pgf",
292+
bbox_inches="tight")

0 commit comments

Comments
 (0)