matplotlib清除 axes 和 figure
一、總結
一句話總結:
plt.cla() # 清除axes,即當前 figure 中的活動的axes,但其他axes保持不變。
plt.clf() # 清除當前 figure 的所有axes,但是不關閉這個 window,所以能繼續復用於其他的 plot。
plt.close() # 關閉 window,如果沒有指定,則指當前 window。
二、matplotlib清除 axes 和 figure
轉自或參考:https://blog.csdn.net/tz_zs/article/details/81393098
____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.
