Skip to content

Don't fallback to agg in tight_layout.get_renderer. #15221

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
May 26, 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
9 changes: 6 additions & 3 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -1501,7 +1501,7 @@ def __init__(self, name, canvas, key, x=0, y=0, guiEvent=None):
self.key = key


def _get_renderer(figure, print_method, *, draw_disabled=False):
def _get_renderer(figure, print_method=None, *, draw_disabled=False):
"""
Get the renderer that would be used to save a `~.Figure`, and cache it on
the figure.
Expand All @@ -1520,8 +1520,11 @@ class Done(Exception):
def _draw(renderer): raise Done(renderer)

with cbook._setattr_cm(figure, draw=_draw):
if print_method is None:
fmt = figure.canvas.get_default_filetype()
print_method = getattr(figure.canvas, f"print_{fmt}")
try:
print_method(io.BytesIO())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dpi was many other things than figure.dpi in my quick skim of the code below, so is it really OK to use figure.dpi here? I'll block because I think this should be answered, but anyone should clear if this is really not a problem. I haven't looked carefully yet.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If _get_renderer is called from print_figure(), then figure.dpi has already been set to match the requested savefig dpi (cbook._setattr_cm(self.figure, dpi=dpi)), so setting it a second time is a noop. If called from tight_layout.get_renderer, OTOH, we do need to pass in the figure dpi -- otherwise it's savefig.dpi which gets used, which is not correct when we want to tight-layout something not for the purpose of saving it.

print_method(io.BytesIO(), dpi=figure.dpi)
except Done as exc:
renderer, = figure._cachedRenderer, = exc.args

Expand Down Expand Up @@ -2089,7 +2092,7 @@ def print_figure(
renderer = _get_renderer(
self.figure,
functools.partial(
print_method, dpi=dpi, orientation=orientation),
print_method, orientation=orientation),
draw_disabled=True)
self.figure.draw(renderer)
bbox_inches = self.figure.get_tightbbox(
Expand Down
15 changes: 15 additions & 0 deletions lib/matplotlib/tests/test_tightlayout.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,3 +310,18 @@ def test_suptitle():
t = ax.set_title("bar")
fig.canvas.draw()
assert st.get_window_extent().y0 > t.get_window_extent().y1


@pytest.mark.backend("pdf")
def test_non_agg_renderer(monkeypatch, recwarn):
unpatched_init = mpl.backend_bases.RendererBase.__init__

def __init__(self, *args, **kwargs):
# Check that we don't instantiate any other renderer than a pdf
# renderer to perform pdf tight layout.
assert isinstance(self, mpl.backends.backend_pdf.RendererPdf)
unpatched_init(self, *args, **kwargs)

monkeypatch.setattr(mpl.backend_bases.RendererBase, "__init__", __init__)
fig, ax = plt.subplots()
fig.tight_layout()
15 changes: 5 additions & 10 deletions lib/matplotlib/tight_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,19 +166,14 @@ def auto_adjust_subplotpars(

def get_renderer(fig):
if fig._cachedRenderer:
renderer = fig._cachedRenderer
return fig._cachedRenderer
else:
canvas = fig.canvas

if canvas and hasattr(canvas, "get_renderer"):
renderer = canvas.get_renderer()
else: # Some noninteractive backends have no renderer until draw time.
cbook._warn_external("tight_layout: falling back to Agg renderer")
from matplotlib.backends.backend_agg import FigureCanvasAgg
canvas = FigureCanvasAgg(fig)
renderer = canvas.get_renderer()

return renderer
return canvas.get_renderer()
else:
from . import backend_bases
return backend_bases._get_renderer(fig, draw_disabled=True)


def get_subplotspec_list(axes_list, grid_spec=None):
Expand Down