Matplotlib offers these functions:
cla() # Clear axis
clf() # Clear figure
close() # Close a figure window
When should I use each function and what exactly does it do?
matplotlibplotpython
Matplotlib offers these functions:
cla() # Clear axis
clf() # Clear figure
close() # Close a figure window
When should I use each function and what exactly does it do?
Best Answer
They all do different things, since matplotlib uses a hierarchical order in which a figure window contains a figure which may consist of many axes. Additionally, there are functions from the pyplot interface and there are methods on the
Figure
class. I will discuss both cases below.pyplot interface
pyplot
is a module that collects a couple of functions that allow matplotlib to be used in a functional manner. I here assume thatpyplot
has been imported asimport matplotlib.pyplot as plt
. In this case, there are three different commands that remove stuff:See
matplotlib.pyplot
Functions:plt.cla()
clears an axis, i.e. the currently active axis in the current figure. It leaves the other axes untouched.plt.clf()
clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.plt.close()
closes a window, which will be the current window, if not specified otherwise.Which functions suits you best depends thus on your use-case.
The
close()
function furthermore allows one to specify which window should be closed. The argument can either be a number or name given to a window when it was created usingfigure(number_or_name)
or it can be a figure instancefig
obtained, i.e., usingfig = figure()
. If no argument is given toclose()
, the currently active window will be closed. Furthermore, there is the syntaxclose('all')
, which closes all figures.methods of the Figure class
Additionally, the
Figure
class provides methods for clearing figures. I'll assume in the following thatfig
is an instance of aFigure
:fig.clf()
clears the entire figure. This call is equivalent toplt.clf()
only iffig
is the current figure.fig.clear()
is a synonym forfig.clf()
Note that even
del fig
will not close the associated figure window. As far as I know the only way to close a figure window is usingplt.close(fig)
as described above.