FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

ENH: add `ax` kwarg to every pyplot function by tacaswell · Pull Request #9111 · matplotlib/matplotlib · GitHub

Repository navigation

ENH: add ax kwarg to every pyplot function - #9111

Closed
tacaswell wants to merge 2 commits into
matplotlib:mainfrom
tacaswell:ENH_ax_into_pyplot
Closed

tacaswell wants to merge 2 commits into
matplotlib:mainfrom
tacaswell:ENH_ax_into_pyplot

Conversation

Copy link
Copy Markdown
Member

This allows passing ax=some_ax into all of the pyplot plotting
functions.

PR Checklist

  • Has Pytest style unit tests
  • Code is PEP 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)

tacaswell added this to the 2.1 (next point release) milestone Aug 28, 2017

anntzer commented Aug 28, 2017

Copy link
Copy Markdown
Contributor

What's the benefit as opposed to just using the OO API, if you really want to specify the figure/axis?

Copy link
Copy Markdown
Member Author

This is the opening pass at something I have been thinking about for a while.

The very short version is that there is currently a major difference between 'built in' plotting (ax.foo(data, style)) and user / third-party plotting (foo(data, style, ax=ax)) and it would be better to reduce. As we do not want third-party tools to be monkey-patching methods on to Axes, we should rotate the main API to look more like functions to put everything on the same footing. The suggested API would then be

def my_plotter(*data, ax, **style):
   ...

This is bread-crumbs leading that direction.

anntzer commented Aug 28, 2017

Copy link
Copy Markdown
Contributor

This actually looks like a reasonable argument (as much as I would like not to admit it...)

WeatherGod commented Aug 28, 2017 via email

Copy link
Copy Markdown
Member

Copy link
Copy Markdown
Contributor

In general I'm ok with the idea. I do think we should think about the idea of plotting objects in this context before proceeding, though.

anntzer commented Aug 28, 2017

Copy link
Copy Markdown
Contributor

Also what's wrong with just using sca() in that case?
Or even

with plt.sca(ax): ...

which is probably going to be less repetitive that having to pass ax again and again.

dopplershift left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

If for no other reason than that this allows using the pyplot interface with an explicit axes, I'm 💯 on this.

Copy link
Copy Markdown
Member Author

I think that this and more complex objects are orthogonal. The objects are about making more complex plots easier to update and work with (ex errorbars) and this is about letting third-party code, or code that takes in not-arrays as input feel like first class citizens next to the 'official'.

I expect there to be plotting functions that take in very non-array things (like a partial sql query!).

It also provides a smoother path to leaving the fully implicit world to the full OO world.

tacaswell added the Release critical For bugs that make the library unusable (segfaults, incorrect plots, etc) and major regressions. label Aug 28, 2017

Copy link
Copy Markdown
Member Author

This is actually pass 2 at this, see #4488

tacaswell force-pushed the ENH_ax_into_pyplot branch 2 times, most recently from b08714c to f26efd9 Compare August 31, 2017 03:06
def test_explict_ax():
fig, (ax1, ax2) = plt.subplots(2)
plt.plot(range(5))
plt.plot(range(5)[::-1], ax=ax1)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

I would just test that len(ax1.lines) == 2 instead of doing an image comp.

test name has typo ("explicit")

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

There should be one line per axes (gca() is surprising! ax2 was created last so it is 'current')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

you got me :-)
but still you should be able to just test how many lines there are on each axis.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Done

Comment thread tools/boilerplate.py Outdated
# A gensym-like facility in case some function takes an
# argument named washold, ax, or ret
washold, ret, ax = 'washold', 'ret', 'ax'
washold, ret = 'washold', 'ret'

anntzer Aug 31, 2017 •
edited
Loading

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

the comment above needs to be updated
side point: I think we should just throw an exception in this case -- the parameter name is part of the API so renaming it seems silly

Comment thread tools/boilerplate.py Outdated
washold, ret = 'washold', 'ret'
bad = set(args) | {varargs, varkw}
while washold in bad or ret in bad or ax in bad:
if 'ax' is set(args):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

I was suggesting to do the same for washold and ret below.

efiring commented Aug 31, 2017

Copy link
Copy Markdown
Member

Even if this turns out to be the way to go, bringing in such a major strategic change with so little discussion and review is not good. Suggestion: leave this out of 2.1, and make it the proposed centerpiece of 2.2, with a very short release cycle--say, Nov. 1 as the target.

Copy link
Copy Markdown
Member Author

It was worth a shot!

I am taking @efiring 's comment as a veto of this going in for 2.1.

Delaying to 2.2 in Nov would give us time to write some collateral around this change, flesh out some of the other implications, and retroactively write a MEP which is probably for the best

tacaswell modified the milestones: 2.2 (next next feature release), 2.1 (next point release) Aug 31, 2017

anntzer commented Aug 31, 2017

Copy link
Copy Markdown
Contributor

Having though a bit about this, right now I belive my preferred take on such an API ("to make pyplot and external functions more symmetrical") would be

with plt.sca(ax): # or a new function
    plt.plot(...)
    seaborn.somemethod(...)
# when sca() is *exited* there is *no* current axes,
# so plt.gca() would return None and plt.plot would error

which seems better than having to pass the same ax again and again.

Copy link
Copy Markdown
Member Author

However this means inside of every function there must be a call to plt.gca(). The other long term goal is to get away from the shared global state of pyplot (so everything GC's reasonable, etc).

Having no current figure/ax is a non-starter. pyplot (and all of it's shared global state) exists as convince methods for people sitting in an interactive shell and I do not think we will ever be able to remove it, just make it possible for people to use without it.

Having a context manager that resets the current axes to what it was before would be a reasonable thing though.

XXX(..., ax=ax) is not that much more onerous than ax.XXX(...)

dstansby removed the Release critical For bugs that make the library unusable (segfaults, incorrect plots, etc) and major regressions. label Oct 14, 2017
tacaswell modified the milestones: needs sorting, v3.1 Jul 7, 2018
tacaswell added the Release critical For bugs that make the library unusable (segfaults, incorrect plots, etc) and major regressions. label Jul 7, 2018

NelleV left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

In terms of code, this looks good, but the PR introduces a backward incompatible change.

On the documentation front, a lot of the docstrings need to be updated to reflect the addition of an optional keyword argument. I'm happy to push the missing documentation.

I'm also concerned about the unit tests. While indeed, this has been tested on one of the pyplot function, I think we should maybe write smoke tests coverage all pyplot functions concerned by this change.

Comment thread lib/matplotlib/pyplot.py Outdated
ax = gca()
else:
ax = args[0]
ax, = args

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

This will fail if args has more arguments than one. If args is can only be one optional argument, why not change *args into an actual optional keyword argument? That would make the code more readible, and more easily documentable than currently.

Note that because of this line we are currently introducing a backward compatible change with this PR.

Comment thread lib/matplotlib/pyplot.py Outdated
"""

fig = gcf()
if fig is None:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

The docstring needs to be update to reflect the addition of an optional keyword argument.

Comment thread lib/matplotlib/pyplot.py Outdated


def box(on=None):
def box(on=None, ax=None):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

The docstring needs to be update to reflect the addition of an optional keyword argument.

Comment thread lib/matplotlib/pyplot.py
loc : {'center', 'left', 'right'}, str, optional
Which title to set, defaults to 'center'

ax : matplotlib.axes.Axes, optional

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

👍

Comment thread lib/matplotlib/pyplot.py Outdated

"""
return gca().set_title(s, *args, **kwargs)
return _pop_or_gca(kwargs).set_title(s, *args, **kwargs)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

The docstring needs to be update to reflect the addition of an optional keyword argument.

tacaswell modified the milestones: v3.5.0, 3.6.0 Jul 8, 2021
timhoffm modified the milestones: v3.6.0, unassigned Apr 30, 2022
story645 modified the milestones: unassigned, needs sorting Oct 6, 2022

Copy link
Copy Markdown
Member Author

rebased to keep the dream alive.

Copy link
Copy Markdown

Since this Pull Request has not been updated in 60 days, it has been marked "inactive." This does not mean that it will be closed, though it may be moved to a "Draft" state. This helps maintainers prioritize their reviewing efforts. You can pick the PR back up anytime - please ping us if you need a review or guidance to move the PR forward! If you do not plan on continuing the work, please let us know so that we can either find someone to take the PR over, or close it.

github-actions Bot added the status: inactive Marked by the “Stale” Github Action label Apr 16, 2023

timhoffm commented Apr 16, 2023 •
edited
Loading

Copy link
Copy Markdown
Member

As a side-note: The place where the ax keyword is most present is the pandas plot API. Unfortunately, they have a different semantic (“if not given, create a new axes” vs. pyplot: “if not given, use the current axes - only if there is no current axes, create a new one).
Not necessarily a blocker, but we have to be aware that this will be a source of confusion.


I've marked this as keep and needs comment/discussion because it really something to investigate, but the correct approach is not yet clear.

timhoffm added status: needs comment/discussion needs consensus on next step keep Items to be ignored by the “Stale” Github Action and removed status: inactive Marked by the “Stale” Github Action labels Apr 16, 2023
This allows passing `ax=some_ax` or `fig=some_fig` into all of the
pyplot plotting functions.

Copy link
Copy Markdown
Member Author

I could not quickly figure out how to convince the generated annotations to not use the fully qualified class names.

Bit confused why it was not hitting these before.

Copy link
Copy Markdown
Member Author

mypy is still also a bit unhappy (it does not like forwarding returns through unconditionally...I guess the fix would be to make the generating code smart enough to drop the return if the wrapped function claims to only ever return None.

Copy link
Copy Markdown
Member Author

This has significantly bit-rotted. I still think this is a good idea, but will close for now.

tacaswell closed this Oct 9, 2025
tacaswell removed this from the future releases milestone Oct 9, 2025

gargcodes2006 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Thanks for contributing this improvement! Adding ax as an implicit input to pyplot functions looks useful for making the API more consistent. I’ll be interested to see how this behaves across different plotting functions and whether the tests cover the expected behavior. Great work!

Copy link
Copy Markdown
Member

@gargcodes2006 please not that this is not implemented right now.

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

keep Items to be ignored by the “Stale” Github Action status: needs comment/discussion needs consensus on next step status: needs rebase

Projects

None yet

Development

Successfully merging this pull request may close these issues.


Back | FazBrowse Home | New Git URL