Skip to content

Deprecate the dryrun parameter to print_foo(). #14134

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 7, 2019

Conversation

anntzer
Copy link
Contributor

@anntzer anntzer commented May 5, 2019

The print_foo() methods of all backends (that implement saving to a
given format -- print_svg saves to svg, etc.) all have an undocumented
dryrun parameter that effectively means "don't actually do the
drawing; just set the _cachedRenderer attribute on the figure" with the
intent of using that renderer object to determine the figure tight bbox
for saving with bbox_inches="tight".

  • This behavior is not actually implemented for the pdf backend, so
    saving to pdf with bbox_inches="tight" will currently fully walk the
    artist tree twice.
  • This is a parameter that needs to be reimplemented again and again for
    all third-party backends (cough cough, mplcairo).

Instead, we can extract that renderer object by fiddling with
Figure.draw (see implementation of _get_renderer), which may not be the
most elegant, but avoids having to reimplement the same functionality
across each backend.

This patch also found that Table's window_extent is incorrect until a
draw() is performed. Fix that problem by correctly setting the table's
text positions in get_window_extent().

PR Summary

PR Checklist

  • Has Pytest style unit tests
  • Code is Flake 8 compliant
  • New features are documented, with examples if plot related
  • Documentation is sphinx and numpydoc compliant
  • Added an entry to doc/users/next_whats_new/ if major new feature (follow instructions in README.rst there)
  • Documented in doc/api/api_changes.rst if API changed in a backward-incompatible way

@anntzer anntzer added this to the v3.2.0 milestone May 5, 2019
The print_foo() methods of all backends (that implement saving to a
given format -- print_svg saves to svg, etc.) all have an undocumented
`dryrun` parameter that effectively means "don't actually do the
drawing; just set the _cachedRenderer attribute on the figure" with the
intent of using that renderer object to determine the figure tight bbox
for saving with bbox_inches="tight".

- This behavior is not actually implemented for the pdf backend, so
  saving to pdf with bbox_inches="tight" will currently fully walk the
  artist tree twice.
- This is a parameter that needs to be reimplemented again and again for
  all third-party backends (cough cough, mplcairo).

Instead, we can extract that renderer object by fiddling with
Figure.draw (see implementation of _get_renderer), which may not be the
most elegant, but avoids having to reimplement the same functionality
across each backend.

This patch also found that Table's window_extent is incorrect until a
draw() is performed.  Fix that problem by correctly setting the table's
text positions in get_window_extent().
@@ -458,6 +458,7 @@ def get_children(self):

def get_window_extent(self, renderer):
"""Return the bounding box of the table in window coords."""
self._update_positions(renderer)
Copy link
Member

Choose a reason for hiding this comment

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

Could you add a quick test for the issue solved by this change?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

A few tests in test_bbox_tight fail without it (they test tight-bboxing tables).

@dstansby dstansby merged commit f620c0e into matplotlib:master May 7, 2019
@anntzer anntzer deleted the dryrun branch May 7, 2019 08:45
@astrofrog
Copy link
Contributor

astrofrog commented May 11, 2019

@anntzer @tacaswell @dstansby - This has broken some functionality in astropy's WCSAxes, specifically when creating plots with aspect='equal', e.g:

from astropy.wcs import WCS
import matplotlib.pyplot as plt

wcs = WCS()
fig = plt.figure(figsize=(3, 3))
ax = fig.add_axes([0.25, 0.25, 0.5, 0.5], projection=wcs, aspect='equal')
ax.set_xlim(0, 10000)
ax.set_ylim(0, 10)
fig.savefig('test.png', bbox_inches='tight')

In this case, the final bounding box is the one as if the aspect ratio had not been set to equal. It makes some kind of sense that this PR would affect this since I seem to recall that Matplotlib will actually first draw the figure without taking into account the equal aspect then update the plot to take into account the aspect, and somehow for WCSAxes this means that it remembers the bounding box before the aspect ratio is actually updated internally.

My question here is whether it's expected that this PR would have the potential to break subclasses of Axes that overwrite draw, and if so, what should likely be changed in subclasses such as WCSAxes? Or should the broken backwards-compatibility be treated as a Matplotlib bug?

@astrofrog
Copy link
Contributor

astrofrog commented May 11, 2019

I've managed to narrow this down to the following minimal example:

import matplotlib.pyplot as plt
from matplotlib.axes import Axes


class MyAxes(Axes):
    def get_tightbbox(self, renderer, *args, **kwargs):
        return self.get_window_extent(renderer)


fig = plt.figure(figsize=(3, 3))
ax = fig.add_axes(MyAxes(fig, [0.25, 0.25, 0.5, 0.5], aspect='equal'))
ax.set_xlim(0, 10000)
ax.set_ylim(0, 1000)
fig.savefig('test.png', bbox_inches='tight')

In WCSAxes we customize get_tightbbox because under certain circumstances we need to customize it (by specifying extra artists), but the above self.get_window_extent(renderer) is meant to be the 'default' behavior. Should this now be changed?

@jklymak
Copy link
Member

jklymak commented May 11, 2019

I think get_tightbbox needs to call apply_aspect. I’m still confused about which way this broke. Is the new image too big or too small?

Note that get_window_extent doesn’t include any decorators or artists on the axes. Usually get_tightbbox does. Note also that we have changed the default artists included to include all axes artists so astropy may want to redo its method of including/excluding artists.

Is the reason this PR broke things because it. Allied the draw twice? I actually think this will end up being derigeur for all the tight and constrained layout calculations. Not very efficient but if you are asking for automated layout you will get better results if you burn a few cpu cycles.

@astrofrog
Copy link
Contributor

The new output image is too large (the example code in my last comment above shows the issue). Good to know about including all artists, I'll investigate whether updating get_tightbbox or removing our custom version fixes things. Thanks!

@tacaswell
Copy link
Member

It looks like https://github.com/matplotlib/matplotlib/pull/14134/files#diff-504c288d675954e4e24de83a19242f4dL2046 was doing more than just getting the renderer (as it was actually triggering the draw methods which updates the bounding boxes).

I am inclined to treat this as an un-intentional and insufficiently warned backward incompatibility break that should be fixed on our side, but one that should be made eventually (and I don't see how to warn this one effectively).

I think if @astrofrog finds a way to fix WCSAxes without too much pain and there is a release of WCSAxes before 3.2 comes out (which at this point will be Nov - Dec of 2019) we should leave this in, otherwise we should back this out for another cycle to give down stream libraries more time to adjust.

At a minimum this needs more verbiage in the API changes docs warning about this problem.

@anntzer
Copy link
Contributor Author

anntzer commented May 11, 2019

The breakage was definitely unintentional. I think we can fix this by adding, after the

renderer = _get_renderer(...)

line, a call to

figure.draw(renderer)

? Happy to provide a PR if that fixes WCSAxes.
Then we still have to walk the draw tree twice (which is less than optimal, but heh), but at least this removes the need for each backend (builtin or 3rd-party) to implement support for dryrun.

@astrofrog
Copy link
Contributor

astrofrog commented May 11, 2019

Changing:

                    renderer = _get_renderer(
                        self.figure,
                        functools.partial(
                            print_method, dpi=dpi, orientation=orientation))

to

                    renderer = _get_renderer(
                        self.figure,
                        functools.partial(
                            print_method, dpi=dpi, orientation=orientation))
                    self.figure.draw(renderer)

Seems to fix the WCSAxes issue. I'll still take a look at whether we can adjust our code to not have to overload get_tightbox though. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants