Skip to content

Disable draw_foo methods on renderer used to estimate tight extents. #16734

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -1489,10 +1489,15 @@ def __init__(self, name, canvas, key, x=0, y=0, guiEvent=None):
self.key = key


def _get_renderer(figure, print_method):
def _get_renderer(figure, print_method, *, draw_disabled=False):
"""
Get the renderer that would be used to save a `~.Figure`, and cache it on
the figure.

If *draw_disabled* is True, additionally replace draw_foo methods on
*renderer* by no-ops. This is used by the tight-bbox-saving renderer,
which needs to walk through the artist tree to compute the tight-bbox, but
for which the output file may be closed early.
"""
# This is implemented by triggering a draw, then immediately jumping out of
# Figure.draw() by raising an exception.
Expand All @@ -1506,8 +1511,14 @@ def _draw(renderer): raise Done(renderer)
try:
print_method(io.BytesIO())
except Done as exc:
figure._cachedRenderer, = exc.args
return figure._cachedRenderer
renderer, = figure._cachedRenderer, = exc.args

if draw_disabled:
for meth_name in dir(RendererBase):
if meth_name.startswith("draw_"):
setattr(renderer, meth_name, lambda *args, **kwargs: None)

return renderer


def _is_non_interactive_terminal_ipython(ip):
Expand Down Expand Up @@ -2058,7 +2069,8 @@ def print_figure(self, filename, dpi=None, facecolor=None, edgecolor=None,
renderer = _get_renderer(
self.figure,
functools.partial(
print_method, dpi=dpi, orientation=orientation))
print_method, dpi=dpi, orientation=orientation),
draw_disabled=True)
self.figure.draw(renderer)
bbox_artists = kwargs.pop("bbox_extra_artists", None)
bbox_inches = self.figure.get_tightbbox(
Expand Down
8 changes: 8 additions & 0 deletions lib/matplotlib/tests/test_backend_pgf.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,3 +291,11 @@ def test_tex_restart_after_error():
fig = plt.figure() # start from scratch
fig.suptitle(r"this is ok")
fig.savefig(BytesIO(), format="pgf")


@needs_xelatex
def test_bbox_inches_tight(tmpdir):
fig, ax = plt.subplots()
ax.imshow([[0, 1], [2, 3]])
fig.savefig(os.path.join(tmpdir, "test.pdf"), backend="pgf",
bbox_inches="tight")