8000 MNT: prefer Figure.clear() as canonical over Figure.clf() by tacaswell · Pull Request #22735 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

MNT: prefer Figure.clear() as canonical over Figure.clf() #22735

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 3 commits into from
Apr 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversatio 8000 ns
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/api/prev_api_changes/api_changes_3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,7 @@ Hold machinery
Setting or unsetting ``hold`` (:ref:`deprecated in version 2.0<v200_deprecate_hold>`) has now
been completely removed. Matplotlib now always behaves as if ``hold=True``.
To clear an axes you can manually use :meth:`~.axes.Axes.cla()`,
or to clear an entire figure use :meth:`~.figure.Figure.clf()`.
or to clear an entire figure use :meth:`~.figure.Figure.clear()`.


Removal of deprecated backends
Expand Down
2 changes: 1 addition & 1 deletion doc/users/prev_whats_new/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3139,7 +3139,7 @@ the `API changes <../../api/api_changes.html>`_.
Fixed a bug in backend_qt4, reported on mpl-dev - DSD

2007-03-26
Removed colorbar_classic from figure.py; fixed bug in Figure.clf() in which
Removed colorbar_classic from figure.py; fixed bug in Figure.clear() in which
_axobservers was not getting cleared. Modernization and cleanups. - EF

2007-03-26
Expand Down
31 changes: 22 additions & 9 deletions lib/matplotlib/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -913,7 +913,7 @@ def _break_share_link(ax, grouper):
# Break link between any twinned axes
_break_share_link(ax, ax._twinned_axes)

def clf(self, keep_observers=False):
def clear(self, keep_observers=False):
"""
Clear the figure.

Expand All @@ -928,7 +928,7 @@ def clf(self, keep_observers=False):

# first clear the axes in any subfigures
for subfig in self.subfigs:
subfig.clf(keep_observers=keep_observers)
subfig.clear(keep_observers=keep_observers)
self.subfigs = []

for ax in tuple(self.axes): # Iterate over the copy.
Expand All @@ -949,13 +949,26 @@ def clf(self, keep_observers=False):

self.stale = True

# synonym for `clf`."""
clear = clf
# synonym for `clear`.
def clf(self, keep_observers=False):
"""
Alias for the `clear()` method.

.. admonition:: Discouraged

The use of ``clf()`` is discouraged. Use ``clear()`` instead.

Parameters
----------
keep_observers: bool, default: False
Set *keep_observers* to True if, for example,
a gui widget is tracking the Axes in the figure.
"""
return self.clear(keep_observers=keep_observers)

# Note: in the docstring below, the newlines in the examples after the
# calls to legend() allow replacing it with figlegend() to generate the
# docstring of pyplot.figlegend.

@_docstring.dedent_interpd
def legend(self, *args, **kwargs):
"""
Expand Down Expand Up @@ -2340,7 +2353,7 @@ def __init__(self,
self.subplotpars = subplotpars

self._axstack = _AxesStack() # track all figure axes and current axes
self.clf()
self.clear()
self._cachedRenderer = None

# list of child gridspecs for this figure
Expand Down Expand Up @@ -2839,10 +2852,10 @@ def set_figheight(self, val, forward=True):
"""
self.set_size_inches(self.get_figwidth(), val, forward=forward)

def clf(self, keep_observers=False):
def clear(self, keep_observers=False):
# docstring inherited
super().clf(keep_observers=keep_observers)
# FigureBase.clf does not clear toolbars, as
super().clear(keep_observers=keep_observers)
# FigureBase.clear does not clear toolbars, as
# only Figure can have toolbars
toolbar = self.canvas.toolbar
if toolbar is not None:
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -953,7 +953,7 @@ def close(fig=None):

def clf():
"""Clear the current figure."""
gcf().clf()
gcf().clear()


def draw():
Expand Down
27 changes: 17 additions & 10 deletions lib/matplotlib/tests/test_figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from matplotlib._api.deprecation import MatplotlibDeprecationWarning
from matplotlib.testing.decorators import image_comparison, check_figures_equal
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from matplotlib.figure import Figure, FigureBase
from matplotlib.layout_engine import (ConstrainedLayoutEngine,
TightLayoutEngine)
from matplotlib.ticker import AutoMinorLocator, FixedFormatter, ScalarFormatter
Expand Down Expand Up @@ -709,7 +709,8 @@ def test_removed_axis():
fig.canvas.draw()


def test_figure_clear():
@pytest.mark.parametrize('clear_meth', ['clear', 'clf'])
def test_figure_clear(clear_meth):
# we test the following figure clearing scenarios:
fig = plt.figure()

Expand All @@ -719,19 +720,19 @@ def test_figure_clear():

# b) a figure with a single unnested axes
ax = fig.add 67E6 _subplot(111)
fig.clear()
getattr(fig, clear_meth)()
assert fig.axes == []

# c) a figure multiple unnested axes
axes = [fig.add_subplot(2, 1, i+1) for i in range(2)]
fig.clear()
getattr(fig, clear_meth)()
assert fig.axes == []

# d) a figure with a subfigure
gs = fig.add_gridspec(ncols=2, nrows=1)
subfig = fig.add_subfigure(gs[0])
subaxes = subfig.add_subplot(111)
fig.clear()
getattr(fig, clear_meth)()
assert subfig not in fig.subfigs
assert fig.axes == []

Expand All @@ -755,15 +756,15 @@ def test_figure_clear():
subaxes = subfig.add_subplot(111)
assert mainaxes in fig.axes
assert subaxes in fig.axes
subfig.clear()
getattr(subfig, clear_meth)()
assert subfig in fig.subfigs
assert subaxes not in subfig.axes
assert subaxes not in fig.axes
assert mainaxes in fig.axes

# e.4) clearing the whole thing
subaxes = subfig.add_subplot(111)
fig.clear()
getattr(fig, clear_meth)()
assert fig.axes == []
assert fig.subfigs == []

Expand All @@ -774,22 +775,28 @@ def test_figure_clear():
assert all(sfig in fig.subfigs for sfig in subfigs)

# f.1) clearing only one subfigure
subfigs[0].clear()
getattr(subfigs[0], clear_meth)()
assert subaxes[0] not in fig.axes
assert subaxes[1] in fig.axes
assert subfigs[1] in fig.subfigs

# f.2) clearing the whole thing
subfigs[1].clear()
getattr(subfigs[1], clear_meth)()
subfigs = [fig.add_subfigure(gs[i]) for i in [0, 1]]
subaxes = [sfig.add_subplot(111) for sfig in subfigs]
assert all(ax in fig.axes for ax in subaxes)
assert all(sfig in fig.subfigs for sfig in subfigs)
fig.clear()
getattr(fig, clear_meth)()
assert fig.subfigs == []
assert fig.axes == []


def test_clf_not_refedined():
for klass in FigureBase.__subclasses__():
# check that subclasses do not get redefined in our Figure subclasses
assert 'clf' not in klass.__dict__


@mpl.style.context('mpl20')
def test_picking_does_not_stale():
fig, ax = plt.subplots()
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/tests/test_usetex.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def test_minus_no_descent(fontsize):
heights = {}
fig = plt.figure()
for vals in [(1,), (-1,), (-1, 1)]:
fig.clf()
fig.clear()
for x in vals:
fig.text(.5, .5, f"${x}$", usetex=True)
fig.canvas.draw()
Expand Down
0