以下是源代码,结果: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.DataFrametodo: need control the max min points."""plt.figure(figsize=(figsize_width, figsize_hight))  # type: plt.figure.Figureax=df_data.plot()  # type: pd.plotting._core.FramePlotMethodsdf_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 scaleplt.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.DataFrametodo: need control the max min points."""df_data.plot(ax=self.ax)  # type: pd.plotting._core.FramePlotMethodsdf_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 scaleplt.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.FramePlotMethodsdf_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 scaleplt.yscale('linear')plt.tight_layout()plt.minorticks_on()plt.savefig(file_path)  # 保存到图片self.tp.update_xlsx_by_sn(sn, fig)  # save to excelplt.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

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

  1. 使用pandas分析医院人群20分钟分段就医人数

    分析医院每20分钟段就医人数情况,找出医院集中就医的时间段.思路首先要对各个时间段的人员进行时间段标记,然后通过分组聚合使用count()函数统计每个时间段的人数. 首先需要导入需要的模块: #导入模 ...

  2. pandas 排序 给excel_给Excel重度用户准备的Pandas教程:用Pandas逐帧还原20个Excel常用操作...

    hi,我是为你们的xio习操碎了心的和鲸社区男运营 我们的网站:和鲸社区 Kesci.com 我们的微信公众号:和鲸社区(ID:heywhale-kesci) 有干货,来! 之前品鉴过各个大佬写的Pa ...

  3. Pandas中常见的20多种数据筛选方法,116张图详解 | 图解Pandas-图文第8篇

    01写在前面 大家好,我是阳哥,欢迎来到「Python数据之道」. 本次是<图解Pandas>系列图文内容的 第 08 篇,主要介绍 Pandas 中常见的数据筛选 . 本文是付费阅读文章 ...

  4. 正大天晴与阿里云合作,AI制药提高化合物筛选准确率20% 新药研发困难重重?正大天晴与阿里云合作用AI寻找解决办法...

    新药研发周期长.投入大,一直是药企的难点问题,但伴随AI加入,这一问题或得到缓解.9月5日,记者获悉正大天晴与阿里云正合作采用AI制药,与传统计算机辅助药物设计方法相比,这套新方法可提高筛选准确率20 ...

  5. 20个html标签及其作用,请写出至少20个html标签,并说说各个标签的功能或作用。...

    用户提问 Basic tags 基 本 标 签 Creates an HTML document 创 建 一 个HTML 文 档 Sets off the title and other inform ...

  6. 纽约出租车旅途时间建模分析

    根据纽约出租车的运营数据,针对客户旅途时间展开分析与建模. import os import pandas as pd import numpy as np from matplotlib.pyplo ...

  7. matplotlib中的色条colormap 及色带colorbar

    colormap 关键只有三个语句, 初始化 jet = cm = plt.get_cmap('Reds') cNorm = colors.Normalize(vmin=0, vmax=5) scal ...

  8. python list转换成array_一文掌握Python【不定期更新】

    目录 一.Numpy 1 基本操作 2 随机数 3 打乱训练数据 4 得到元素的最值 5 拼接数组 6 得到函数的信息 7 得到累乘即各项相乘的结果 8 判断一个数是否在数组中 9 数组的变换 10 ...

  9. python模块(5)-Matplotlib 简易使用教程

    Matplotlib简易使用教程 0.matplotlib的安装 1.导入相关库 2.画布初始化 2.1 隐式创建 2.2 显示创建 2.3 设置画布大小 2.4 plt.figure()常用参数 3 ...

  10. task05 PyTorch可视化

    PyTorch可视化 1. 可视化网络结构 使用torchinfo工具包,学习网络结构可视化的方案 import os import numpy as np import torch import t ...

最新文章

  1. 【简明书】机器学习用例书册
  2. python玩王者荣耀皮肤_利用Python完成对王者荣耀英雄全皮肤的下载
  3. python工程师薪资坑吗-不在打工就在找坑的路上,3年+程序员都爱跳槽?
  4. OpenGL中的reshape函数(整理)
  5. python操作mysql数据库 内存占用100_python操作MySQL数据库
  6. RuntimeException:java.lang.ClassNotFoundException: Class wordcount.WordCountMapper not fonud
  7. 大整数乘法(信息学奥赛一本通-T1174)
  8. 西安计算机二级12月,2017年12月计算机二级MS Office习题答案(一)
  9. 详解Java的交互式编程环境:jshell
  10. jk背带是什么意思_JK 制服和 LO 装 (科普向)
  11. windows 10 连接android手机助手,Win10手机助手怎么用?win10手机助手使用方法
  12. UE4 初学者内容包介绍
  13. 如何做好PPT——画图篇
  14. 闩锁和锁(Latches and Locks)
  15. 针对WIN10安卓模拟器蓝屏的解决办法
  16. konga--添加service和rouce详细步骤
  17. ubuntu 桌面任务栏不见解决方案
  18. python添加背景音乐
  19. 12月份参加工作的年假怎么休_12月份满一年的,年假必须在12月份休完吗?
  20. 我是如何使用树莓派击落劫持无人机

热门文章

  1. web工程师的自我修养
  2. 【iccv2021】Vision-Language Transformer and Query Generation for Referring Segmentation
  3. Unity笔记-29-ARPG游戏项目-05-简易的战斗系统
  4. 《关键对话》要点整理
  5. 60帧究级豪华观影体验!potplayer通过bluesky补帧!
  6. python调用so库
  7. BBR:Congestion-Based Congestion Control解读
  8. adb如何在linux下安装目录,Linux下Android ADB驱动安装详解
  9. 安卓手机优化,修改build.prop
  10. 智能管家项目总结(1)