【matplotlib】 之 清理、清除 axes 和 figure (plt.cla、plt.clf、plt.close)

____tz_zs

figure 的重复利用能大大节约时间,但是 matplotlib 维护的 figure 有数量上限(RuntimeWarning: More than 20 figures have been opened.)。并且,不断的创建新的 figure 实例,很容易造成内存泄漏,而应合理的复用,能大大的提高运行速度。此外,在某些情况下,不清理 figure 将有可能造成在第一幅中 plot 的线再次出现在第二幅图中。

以下包括:
plt.cla() # 清除axes,即当前 figure 中的活动的axes,但其他axes保持不变。
plt.clf() # 清除当前 figure 的所有axes,但是不关闭这个 window,所以能继续复用于其他的 plot。
plt.close() # 关闭 window,如果没有指定,则指当前 window。

plt.cla()

plt.cla() # 清除axes,即当前 figure 中的活动的axes,但其他axes保持不变。

pyplot.py 源码

# This function was autogenerated by boilerplate.py.  Do not edit as
# changes will be lost
@docstring.copy_dedent(Axes.cla)
def cla():
    ret = gca().cla()
    return ret

axes/_base.py 源码

def cla(self):
    """Clear the current axes."""
    # Note: this is called by Axes.__init__()

    # stash the current visibility state
    ......
    ......
    ......

plt.clf()

plt.clf() # 清除当前 figure 的所有axes,但是不关闭这个 window,所以能继续复用于其他的 plot。

pyplot.py 源码

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

figure.py 源码

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

    Set *keep_observers* to True if, for example,
    a gui widget is tracking the axes in the figure.
    """
    self.suppressComposite = None
    self.callbacks = cbook.CallbackRegistry()

    for ax in tuple(self.axes):  # Iterate over the copy.
        ax.cla()
        self.delaxes(ax)         # removes ax from self._axstack

    toolbar = getattr(self.canvas, 'toolbar', None)
    if toolbar is not None:
        toolbar.update()
    self._axstack.clear()
    self.artists = []
    self.lines = []
    self.patches = []
    self.texts = []
    self.images = []
    self.legends = []
    if not keep_observers:
        self._axobservers = []
    self._suptitle = None
    self.stale = True

plt.close()

plt.close() # 关闭 window,如果没有指定,则指当前 window。

pyplot.py 源码

def close(*args):
    """
    Close a figure window.

    ``close()`` by itself closes the current figure

    ``close(fig)`` closes the `~.Figure` instance *fig*

    ``close(num)`` closes the figure number *num*

    ``close(name)`` where *name* is a string, closes figure with that label

    ``close('all')`` closes all the figure windows
    """

    if len(args) == 0:
        figManager = _pylab_helpers.Gcf.get_active()
        if figManager is None:
            return
        else:
            _pylab_helpers.Gcf.destroy(figManager.num)
    elif len(args) == 1:
        arg = args[0]
        if arg == 'all':
            _pylab_helpers.Gcf.destroy_all()
        elif isinstance(arg, six.integer_types):
            _pylab_helpers.Gcf.destroy(arg)
        elif hasattr(arg, 'int'):
            # if we are dealing with a type UUID, we
            # can use its integer representation
            _pylab_helpers.Gcf.destroy(arg.int)
        elif isinstance(arg, six.string_types):
            allLabels = get_figlabels()
            if arg in allLabels:
                num = get_fignums()[allLabels.index(arg)]
                _pylab_helpers.Gcf.destroy(num)
        elif isinstance(arg, Figure):
            _pylab_helpers.Gcf.destroy_fig(arg)
        else:
            raise TypeError('Unrecognized argument type %s to close' % type(arg))
    else:
        raise TypeError('close takes 0 or 1 arguments')

使用例子:

fig = plt.gcf() #获取当前figure

plt.close(fig) #关闭传入的 figure 对象

或者:

plt.close('all') #关闭所有 figure windows

参考:

warning-about-too-many-open-figures
matplotlib 之 RuntimeWarning: More than 20 figures have been opened.

你可能感兴趣的:(#,科学计算库)