python之matplotlib学习绘制动态更新图实例代码


Posted in Python onJanuary 23, 2018

简介

通过定时器Timer触发事件,定时更新绘图,可以形成动态更新图片。下面的实例是学习《matplotlib for python developers》一文的笔记。

实现

实现代码及简单介绍

通过self.user = self.user[1:] + [temp],每次删除列表的第一元素,在其尾部添加新的元素。这样完成user数据的动态更新。其他详细的解释见文中的注释部分。

#-*-coding:utf-8-*- 
import wx 
from matplotlib.figure import Figure 
import matplotlib.font_manager as font_manager 
import numpy as np 
from matplotlib.backends.backend_wxagg import \ 
 FigureCanvasWxAgg as FigureCanvas 
# wxWidgets object ID for the timer 
TIMER_ID = wx.NewId() 
# number of data points 
POINTS = 300 
 
class PlotFigure(wx.Frame): 
  """Matplotlib wxFrame with animation effect""" 
  def __init__(self): 
    wx.Frame.__init__(self, None, wx.ID_ANY, title="CPU Usage Monitor", size=(600, 400)) 
    # Matplotlib Figure 
    self.fig = Figure((6, 4), 100) 
    # bind the Figure to the backend specific canvas 
    self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig) 
    # add a subplot 
    self.ax = self.fig.add_subplot(111) 
    # limit the X and Y axes dimensions 
    self.ax.set_ylim([0, 100]) 
    self.ax.set_xlim([0, POINTS]) 
     
    self.ax.set_autoscale_on(False) 
    self.ax.set_xticks([]) 
    # we want a tick every 10 point on Y (101 is to have 10 
    self.ax.set_yticks(range(0, 101, 10)) 
    # disable autoscale, since we don't want the Axes to ad 
    # draw a grid (it will be only for Y) 
    self.ax.grid(True) 
    # generates first "empty" plots 
    self.user = [None] * POINTS 
    self.l_user,=self.ax.plot(range(POINTS),self.user,label='User %') 
 
    # add the legend 
    self.ax.legend(loc='upper center', 
              ncol=4, 
              prop=font_manager.FontProperties(size=10)) 
    # force a draw on the canvas() 
    # trick to show the grid and the legend 
    self.canvas.draw() 
    # save the clean background - everything but the line 
    # is drawn and saved in the pixel buffer background 
    self.bg = self.canvas.copy_from_bbox(self.ax.bbox) 
    # bind events coming from timer with id = TIMER_ID 
    # to the onTimer callback function 
    wx.EVT_TIMER(self, TIMER_ID, self.onTimer) 
 
  def onTimer(self, evt): 
    """callback function for timer events""" 
    # restore the clean background, saved at the beginning 
    self.canvas.restore_region(self.bg) 
        # update the data 
    temp =np.random.randint(10,80) 
    self.user = self.user[1:] + [temp] 
    # update the plot 
    self.l_user.set_ydata(self.user) 
    # just draw the "animated" objects 
    self.ax.draw_artist(self.l_user)# It is used to efficiently update Axes data (axis ticks, labels, etc are not updated) 
    self.canvas.blit(self.ax.bbox) 
if __name__ == '__main__': 
  app = wx.PySimpleApp() 
  frame = PlotFigure() 
  t = wx.Timer(frame, TIMER_ID) 
  t.Start(50) 
  frame.Show() 
  app.MainLoop()

运行结果如下所示:

python之matplotlib学习绘制动态更新图实例代码

疑问

但程序运行在关闭的时候会出现应用程序错误,不知道什么问题。python不是有垃圾回收机制吗,难道是内存泄露?

猜测的原因可能是在关闭的时候正在绘图故导致应用程序出错。通过添加Frame的析构函数,停止更新则不会出现问题。

def __del__( self ): 
  t.Stop()

总结

以上就是本文关于python之matplotlib学习绘制动态更新图实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

Python 相关文章推荐
讲解Python中for循环下的索引变量的作用域
Apr 15 Python
使用PDB简单调试Python程序简明指南
Apr 25 Python
python PIL模块与随机生成中文验证码
Feb 27 Python
django orm 通过related_name反向查询的方法
Dec 15 Python
Python替换月份为英文缩写的实现方法
Jul 15 Python
Django接收post前端返回的json格式数据代码实现
Jul 31 Python
Python学习笔记之列表和成员运算符及列表相关方法详解
Aug 22 Python
Python发送手机动态验证码代码实例
Feb 28 Python
浅谈ROC曲线的最佳阈值如何选取
Feb 28 Python
pytorch 把图片数据转化成tensor的操作
Mar 04 Python
python 如何获取页面所有a标签下href的值
May 06 Python
OpenCV中resize函数插值算法的实现过程(五种)
Jun 05 Python
彻底搞懂Python字符编码
Jan 23 #Python
Python实现PS滤镜的万花筒效果示例
Jan 23 #Python
python处理csv数据动态显示曲线实例代码
Jan 23 #Python
Python+matplotlib实现华丽的文本框演示代码
Jan 22 #Python
CentOS7.3编译安装Python3.6.2的方法
Jan 22 #Python
Python OpenCV实现图片上输出中文
Jan 22 #Python
python批量替换页眉页脚实例代码
Jan 22 #Python
You might like
单位速度在实战中的运用
2020/03/04 星际争霸
mysql5的sql文件导入到mysql4的方法
2008/10/19 PHP
PHP无敌近乎加密方式!
2010/07/17 PHP
php实现的DateDiff和DateAdd时间函数代码分享
2014/08/16 PHP
php基于base64解码图片与加密图片还原实例
2014/11/03 PHP
利用switch语句进行多选一判断的实例代码
2016/11/14 PHP
php+ajax简单实现全选删除的方法
2016/12/06 PHP
学习thinkphp5.0验证类使用方法
2017/11/16 PHP
关于js中window.location.href,location.href,parent.location.href,top.location.href的用法与区别
2010/10/18 Javascript
JavaScript.The.Good.Parts阅读笔记(二)作用域&闭包&减缓全局空间污染
2010/11/16 Javascript
javascript获得服务器端控件的ID的实现代码
2011/12/28 Javascript
jQuery语法高亮插件支持各种程序源代码语法着色加亮
2013/04/27 Javascript
JSONP获取Twitter和Facebook文章数的具体步骤
2014/02/24 Javascript
js通过八个点 拖动改变div大小的实现方法
2014/03/05 Javascript
jquery如何根据值设置默认的选中项
2014/03/17 Javascript
JavaScript中一个奇葩的IE浏览器判断方法
2014/04/16 Javascript
bootstrap的3级菜单样式,支持母版页保留打开状态实现方法
2016/11/10 Javascript
jquery做个日期选择适用于手机端示例
2017/01/10 Javascript
angular forEach方法遍历源码解读
2017/01/25 Javascript
提高JavaScript执行效率的23个实用技巧
2017/03/01 Javascript
Angular中ng-options下拉数据默认值的设定方法
2017/06/21 Javascript
weebox弹出窗口不居中显示的解决方法
2017/11/27 Javascript
js中bool值的转换及“&&”、“||”、 “!!”详解
2017/12/21 Javascript
详解webpack运行Babel教程
2018/06/13 Javascript
微信小程序wx.navigateTo方法里的events参数使用详情及场景
2020/01/07 Javascript
react实现复选框全选和反选组件效果
2020/08/25 Javascript
在vscode 中设置 vue模板内容的方法
2020/09/02 Javascript
简单谈谈python中的多进程
2016/11/06 Python
python 解决pycharm运行py文件只有unittest选项的问题
2020/09/01 Python
如何通过python检查文件是否被占用
2020/12/18 Python
丝芙兰波兰:Sephora.pl
2018/03/25 全球购物
食品安全演讲稿
2014/09/01 职场文书
党性心得体会
2014/09/03 职场文书
简单谈谈Python面向对象的相关知识
2021/06/28 Python
使用redis实现延迟通知功能(Redis过期键通知)
2021/09/04 Redis
volatile保证可见性及重排序方法
2022/08/05 Java/Android