Skip to content

Add option to gcf/gca to disable new figure/axes creation. #20773

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

Closed
wants to merge 1 commit into from
Closed
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
29 changes: 19 additions & 10 deletions lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -1482,15 +1482,25 @@ def sca(self, a):
return a

@docstring.dedent_interpd
def gca(self, **kwargs):
def gca(self, *, create_if_none=True, **kwargs):
"""
Get the current Axes, creating one if necessary.
Get the current Axes.

The following kwargs are supported for ensuring the returned Axes
adheres to the given projection etc., and for Axes creation if
the active Axes does not exist:
Parameters
----------
create_if_none : bool, default: True
*create_if_none* controls this method's behavior if there is no
current Axes: a new one is created if *create_if_none* is True (the
default); None is returned if *create_if_none* is False.

%(Axes:kwdoc)s
Other Parameters
----------------
**kwargs
The kwargs listed below are supported for ensuring the returned
Axes adheres to the given projection etc., and for Axes creation if
the active Axes does not exist. This behavior is deprecated.

%(Axes:kwdoc)s
"""
if kwargs:
_api.warn_deprecated(
Expand All @@ -1502,10 +1512,9 @@ def gca(self, **kwargs):
"new axes with default keyword arguments. To create a new "
"axes with non-default arguments, use plt.axes() or "
"plt.subplot().")
if self._axstack.empty():
return self.add_subplot(1, 1, 1, **kwargs)
else:
return self._axstack()
return (self._axstack() if not self._axstack.empty() else
self.add_subplot(1, 1, 1, **kwargs) if create_if_none else
None)

def _gci(self):
# Helper for `~matplotlib.pyplot.gci`. Do not use elsewhere.
Expand Down
49 changes: 36 additions & 13 deletions lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -815,18 +815,22 @@ def _auto_draw_if_interactive(fig, val):
fig.canvas.draw_idle()


def gcf():
def gcf(*, create_if_none=True):
"""
Get the current figure.

If no current figure exists, a new one is created using
`~.pyplot.figure()`.
Parameters
----------
create_if_none : bool, default: True
*create_if_none* controls this method's behavior if there is no
current figure: a new one is created with `~.pyplot.figure()`
if *create_if_none* is True (the default); None is returned if
*create_if_none* is False.
"""
manager = _pylab_helpers.Gcf.get_active()
if manager is not None:
return manager.canvas.figure
else:
return figure()
return (manager.canvas.figure if manager is not None else
figure() if create_if_none else
None)


def fignum_exists(num):
Expand Down Expand Up @@ -954,6 +958,31 @@ def figlegend(*args, **kwargs):

## Axes ##

def gca(*, create_if_none=True, **kwargs):
"""
Get the current Axes.

Parameters
----------
create_if_none : bool, default: True
*create_if_none* controls this functions's behavior if there is no
current Axes: a new one is created if *create_if_none* is True (the
default); None is returned if *create_if_none* is False.

Other Parameters
----------------
**kwargs
The kwargs listed below are supported for ensuring the returned
Axes adheres to the given projection etc., and for Axes creation if
the active Axes does not exist. This behavior is deprecated.

%(Axes:kwdoc)s
"""
fig = gcf(create_if_none=create_if_none)
return (None if fig is None
else fig.gca(create_if_none=create_if_none, **kwargs))


@docstring.dedent_interpd
def axes(arg=None, **kwargs):
"""
Expand Down Expand Up @@ -2484,12 +2513,6 @@ def figtext(x, y, s, fontdict=None, **kwargs):
return gcf().text(x, y, s, fontdict=fontdict, **kwargs)


# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Figure.gca)
def gca(**kwargs):
return gcf().gca(**kwargs)


# Autogenerated by boilerplate.py. Do not edit as changes will be lost.
@_copy_docstring_and_deprecators(Figure._gci)
def gci():
Expand Down
3 changes: 3 additions & 0 deletions lib/matplotlib/tests/test_figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ def test_align_labels():
def test_figure_label():
# pyplot figure creation, selection, and closing with label/number/instance
plt.close('all')
assert plt.gcf(create_if_none=False) is None
fig_today = plt.figure('today')
plt.figure(3)
plt.figure('tomorrow')
Expand Down Expand Up @@ -150,6 +151,8 @@ def test_figure_legend():
def test_gca():
fig = plt.figure()

assert plt.gca(create_if_none=False) is None

with pytest.raises(TypeError):
assert fig.add_axes() is None

Expand Down
1 change: 0 additions & 1 deletion tools/boilerplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,6 @@ def boilerplate_gen():
_figure_commands = (
'figimage',
'figtext:text',
'gca',
'gci:_gci',
'ginput',
'subplots_adjust',
Expand Down