首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

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

  • 25-03-03 22:02
  • 2125
  • 6069
blog.csdn.net

____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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

axes/_base.py 源码

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

    # stash the current visibility state
    ......
    ......
    ......
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

plt.clf()

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

pyplot.py 源码

def clf():
     """
     Clear the current figure.
     """
     gcf().clf()
  • 1
  • 2
  • 3
  • 4
  • 5

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

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')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

使用例子:

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

plt.close(fig) #关闭传入的 figure 对象
  • 1
  • 2
  • 3

或者:

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

参考:

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

文章知识点与官方知识档案匹配,可进一步学习相关知识
Python入门技能树绘图库MatplotlibMatplotlib快速入门416654 人正在系统学习中
注:本文转载自blog.csdn.net的tz_zs的文章"https://blog.csdn.net/tz_zs/article/details/81393098"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2491) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top