Pandas RuntimeWarning: More than 20 figures have been opened. Figures created plt.close()也不起作用

2023-05-16

以下是源代码,结果:function里有个for循环,在每一次循环都有plt.close(),但是还是报错:

More than 20 figures have been opened. Figures created 

    def generate_plot(self, sn, df_data, df_limiter, file_path):
        """
        Generate the plot picture and fig data by pandas.DataFrame
        todo: need control the max min points.
        """
        plt.figure(figsize=(figsize_width, figsize_hight))  # type: plt.figure.Figure
        ax=df_data.plot()  # type: pd.plotting._core.FramePlotMethods
        df_limiter.plot(ax=ax, c='r',legend=False)

      
        plt.grid(True, which="both", ls="-")
        plt.title(sn + "fail_rate_des", fontdict={'fontsize': 1})
        plt.xlabel('Frequency(Hz)', fontsize=1)
        plt.ylabel('(dB)', fontsize=1)
        plt.xscale('log')  # Used to resolve x scale
        plt.yscale('linear')
        plt.tight_layout()
        # plt.legend(loc=0)
        plt.minorticks_on()
        plt.savefig(file_path)
        plt.close()

  def f():
    for ...
       self.generate_plot(.....)

调试的时候发现是: 创建的ax对象一直是同一个,plt.close并没有重置它。

如果你创建了太多的 figure, 对象,你会收到这个警告。

使用以下代码,能清除并且关闭掉 figure 对象。

解决办法:使用plt.close("all"),关闭所有 

plt.cla()
plt.close("all")

如果你需要画很多图,这样频繁的 “创建→清除” 是会拖慢你的代码运行速度的。最好的办法是,只创建一个 figure 对象,在画下一个图之前,使用 plt.cla() 清理掉 axes,这样可以复用 figure。

遇到:第一个图有数据,后面图都为空白,只有画布:

一种情况是

第一个情况是:我同时执行.clf(), .cla()。 删除plt.clf()即可。

plt.clf()
plt.cla()
# plt.close()

加速实现:

在for循环外创建figure,ax对象,

每次生成图片的时候plt.cla()执行一次清除,

最后for循环外plt.close("all")

#

    def generate_plot(self, sn, df_data, df_limiter, file_path):
        """
        Generate the plot picture and fig data by pandas.DataFrame
        todo: need control the max min points.
        """
        df_data.plot(ax=self.ax)  # type: pd.plotting._core.FramePlotMethods
        df_limiter.plot(ax=self.ax, c='r',legend=False)
        plt.grid(True, which="both", ls="-")
        plt.title(sn + "fail_rate_des", fontdict={'fontsize': 1})
        plt.xlabel('Frequency(Hz)', fontsize=1)
        plt.ylabel('(dB)', fontsize=1)
        plt.xscale('log')  # Used to resolve x scale
        plt.yscale('linear')
        plt.tight_layout()
        # plt.legend(loc=0)
        plt.minorticks_on()
        plt.savefig(file_path)
        plt.cla()
        #plt.close()

  def f():
    self.fig, self.ax = plt.subplots()
    for ...
       self.generate_plot(.....)
    
    plt.close("all")

一共是生成24个图片,大概1900个数据点。加速之前是:13.269s, 加速之后基本在12.2s左右,快了1s。

注:曲线叠加在一张图片上问题

以上加速,如要生成self.fig,用xlwings 这个库把self.fig插入excel会出现,plt.clf(), plt.cla()都失效,图片会重复叠加在最后一张图。

以下是解决插入excel图片重叠生成在一个图片上问题,还是得每次创建一次fig,然后再plot,不能用全局fig.

         fig,ax=plt.subplots(clear=True)
        df_data.plot(ax=ax)  # type: pd.plotting._core.FramePlotMethods
        df_limiter.plot(ax=ax, c='r', legend=False)
        plt.grid(True, which="both", ls="-")
        plt.title(sn + "fail_rate_des", fontdict={'fontsize': 5})
        plt.xlabel('Frequency(Hz)', fontsize=5)
        plt.ylabel('(dB)', fontsize=5)
        plt.xscale('log')  # Used to resolve x scale
        plt.yscale('linear')
        plt.tight_layout()
        plt.minorticks_on()
        plt.savefig(file_path)  # 保存到图片
        self.tp.update_xlsx_by_sn(sn, fig)  # save to excel
        plt.cla()

# self.tp.update_xlsx_by_sn()主要是执行插入图片: 
self.sheet.pictures.add(fig, left=self.sheet.range(cell_value).left,top=self.sheet.range(cell_value).top)  # 在G2单元格插入

官方文档:

RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam figure.max_open_warning).
max_open_warning, RuntimeWarning)

If you intend to knowingly keep many plots in memory, but don't want to be warned about it, you can update your options prior to generating figures.

plt.rcParams.update({'figure.max_open_warning': 0})

plt.cla() # clear a axis
plt.clf()# clear the entire current figure with all its axes, but leaved the window opened, such that it may be reused for other plots;
plt.close()# close the window,which will be the current window,
plt.close('all')will close all open figures

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pandas RuntimeWarning: More than 20 figures have been opened. Figures created plt.close()也不起作用 的相关文章

随机推荐

  • SONiC(2):手动运行sonic-vs

    SONiC的testbed都是用ansible自动部署的 xff0c 下面尝试手动来创建 另外最新的sonic vs可以从这里下载 准备工作 ansible生成的vlab 01这个虚机的vir配置xml文件如下 testbed 64 u18
  • SONiC vs testbed搭建

    准备工作 一台安装Ubuntu18 04的系统 xff0c 内存建议不少于16G 需要支持kvm虚拟化安装ssh server sudo apt update y sudo apt openssh server y 设置sudo免密 sud
  • 2. 安装GNOME和KDE图形化桌面

    安装GNOME和KDE图形化桌面 1 使用CD DVD介质配置本地Yum源2 安装GNOME图形化桌面2 1 安装GNOME xff1a 2 2 设置在系统启动时进入图形化桌面3 安装KDE图形化桌面3 1 安装KDE xff1a 3 2
  • 复位电路的几种设计

    本人转自 xff1a http hi baidu com yinweini2 item 48ba4f12f54587711009b591 复位源是导致单片机内部复位操作的源泉 xff0c 大致可分为七种 xff1a 上电复位 xff08 P
  • Hadoop入门经典:WordCount

    以下程序在hadoop1 2 1上测试成功 本例先将源代码呈现 xff0c 然后详细说明执行步骤 xff0c 最后对源代码及执行过程进行分析 一 源代码 package org jediael hadoopdemo wordcount im
  • Jlink 采用 SWD 模式下载电路接法

    在Jlink上 xff1a 对应的电路图为 xff1a 其中要使用的是 Pin1 gt vcc Pin7 gt SWDIO Pin9 gt SWCLK Pin4 gt GND 其他GND 引脚也可 在对于的开发板 xff08 举例 xff1
  • ubuntu系统硬盘温度过高的解决方法

    一 更改swap分区设置 在ubuntu 里面 xff0c swappiness的值的大小对如何使用swap分区是有着很大的联系的 swappiness 61 0的时候表示最大限度使用物理内存 xff0c 然后才是 swap空间 xff0c
  • MBus协议详解(一)

    看了许多关于MBus协议的资料 xff0c 感觉说的不具体 不完整 也不系统 xff0c 本人准备结合一个具体的产品实现 xff0c 从理论和实现上对MBus协议做一个详细的论述 xff0c 如有不当之处 xff0c 欢迎讨论 1 介绍 M
  • MBus协议详解(二)

    4 4 slave 设计 传输特性 xff1a slaves 被设计为具有两种不同恒定 sink 电流 xff0c 因此在总线上电压有 1V 的变化的时候 xff0c sink 电流的变化一定不能超过 0 2 为了传输一个 Mark xff
  • 多个进程对同一文件写入的问题

    转载 讨论关于并发环境下 xff0c 多个进程对同一文件写入的问题 xff0c 我们会涉及到文件共享的知识 在开始之前 xff0c 我们先讨论一些有关文件共享的知识 1 文件共享 Unix系统支持在不同进程间共享打开的文件 为此 xff0c
  • Linux内核里的DebugFS

    DebugFS xff0c 顾名思义 xff0c 是一种用于内核调试的虚拟文件系统 xff0c 内核开发者通过debugfs和用户空间交换数据 类似的虚拟文件系统还有procfs和sysfs等 xff0c 这几种虚拟文件系统都并不实际存储在
  • linux 只获取dns服务器地址

    有一款设备需要使用静态ip xff0c 但是还要用到dns解析域名 我的想法是定时去查看 etc resolve conf文件 xff0c 如果为空 xff0c 则获取一次dns 在嵌入式linux中 xff0c 我们使用busybox的u
  • linux更新文件

    最近发现很多同学不知道线上操作替换文件的要点 所以又整理了一下 线上替换一个正在运行进程的文件时 xff08 包括二进制 动态库 需要读取的资源文件等 xff09 应避免使用cp scp操作 而需要使用mv rsync作为替代 原因 xff
  • 大型网站架构与自动化运维——ISCSI安装配置

    ISCSI安装配置 一 存储简述 1 DAS xff1a 即直连方式存储 xff0c 英文全称是Direct Attached Storage 直接附加存储 顾名思义 xff0c 在这种方式中 xff0c 存储设备是通过电缆 xff08 通
  • Homebrew brew安装报错:Failed to connect to raw.githubusercontent.com port 443: Operation timed out

    报错 xff1a Failed to connect to raw githubusercontent com port 443 Operation timed out 解决方案 liukeruideMacBook Pro liukerui
  • 正则表达式中(?:)、(?=)以及(?!)等的用法

    out 61 re findall r 39 d 43 61 abc 39 34 1abc 34 只抽取数字 xff0c 并且该数字后面跟的字符是 34 abc 34 print out out1 61 re findall r 39 d
  • Oracle 12C rman备份的坑,搞不好就会hang死

    RMAN Backup to Platform Temporarily Creates DMP File in ORACLE HOME dbs 文档 ID 2349921 1 This has been reported as BUG 25
  • Linux 上安装配置 VNC Server

    一 简介 VNC Virtual Network Console xff0c 即 虚拟网络控制台 它是一款优秀的远程控制工具软件 xff0c 而且是基于 UNIX 和 Linux 操作系统的免费开源的 1 优点 远程控制能力强大 xff0c
  • Xshell能ping通但连不上CentOS 7

    转 xff1a https blog csdn net trackle400 article details 52755571 在虚拟机 xff08 Vmware Workstation xff09 下 xff0c 安装了CentOS7 x
  • Pandas RuntimeWarning: More than 20 figures have been opened. Figures created plt.close()也不起作用

    以下是源代码 xff0c 结果 xff1a function里有个for循环 xff0c 在每一次循环都有plt close xff0c 但是还是报错 xff1a More than 20 figures have been opened