Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 4d8063f

Browse files
authored
Merge pull request #16734 from anntzer/tightdisabledraw
Disable draw_foo methods on renderer used to estimate tight extents.
2 parents 9c819c0 + cd519f8 commit 4d8063f

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

lib/matplotlib/backend_bases.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1489,10 +1489,15 @@ def __init__(self, name, canvas, key, x=0, y=0, guiEvent=None):
14891489
self.key = key
14901490

14911491

1492-
def _get_renderer(figure, print_method):
1492+
def _get_renderer(figure, print_method, *, draw_disabled=False):
14931493
"""
14941494
Get the renderer that would be used to save a `~.Figure`, and cache it on
14951495
the figure.
1496+
1497+
If *draw_disabled* is True, additionally replace draw_foo methods on
1498+
*renderer* by no-ops. This is used by the tight-bbox-saving renderer,
1499+
which needs to walk through the artist tree to compute the tight-bbox, but
1500+
for which the output file may be closed early.
14961501
"""
14971502
# This is implemented by triggering a draw, then immediately jumping out of
14981503
# Figure.draw() by raising an exception.
@@ -1506,8 +1511,14 @@ def _draw(renderer): raise Done(renderer)
15061511
try:
15071512
print_method(io.BytesIO())
15081513
except Done as exc:
1509-
figure._cachedRenderer, = exc.args
1510-
return figure._cachedRenderer
1514+
renderer, = figure._cachedRenderer, = exc.args
1515+
1516+
if draw_disabled:
1517+
for meth_name in dir(RendererBase):
1518+
if meth_name.startswith("draw_"):
1519+
setattr(renderer, meth_name, lambda *args, **kwargs: None)
1520+
1521+
return renderer
15111522

15121523

15131524
def _is_non_interactive_terminal_ipython(ip):
@@ -2058,7 +2069,8 @@ def print_figure(self, filename, dpi=None, facecolor=None, edgecolor=None,
20582069
renderer = _get_renderer(
20592070
self.figure,
20602071
functools.partial(
2061-
print_method, dpi=dpi, orientation=orientation))
2072+
print_method, dpi=dpi, orientation=orientation),
2073+
draw_disabled=True)
20622074
self.figure.draw(renderer)
20632075
bbox_artists = kwargs.pop("bbox_extra_artists", None)
20642076
bbox_inches = self.figure.get_tightbbox(

lib/matplotlib/tests/test_backend_pgf.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,3 +291,11 @@ def test_tex_restart_after_error():
291291
fig = plt.figure() # start from scratch
292292
fig.suptitle(r"this is ok")
293293
fig.savefig(BytesIO(), format="pgf")
294+
295+
296+
@needs_xelatex
297+
def test_bbox_inches_tight(tmpdir):
298+
fig, ax = plt.subplots()
299+
ax.imshow([[0, 1], [2, 3]])
300+
fig.savefig(os.path.join(tmpdir, "test.pdf"), backend="pgf",
301+
bbox_inches="tight")

0 commit comments

Comments
 (0)