Python使用matplotlib绘制动画的方法


Posted in Python onMay 20, 2015

本文实例讲述了Python使用matplotlib绘制动画的方法。分享给大家供大家参考。具体分析如下:

matplotlib从1.1.0版本以后就开始支持绘制动画

下面是几个的示例:

第一个例子使用generator,每隔两秒,就运行函数data_gen:

# -*- coding: utf-8 -*-  
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
fig = plt.figure() 
axes1 = fig.add_subplot(111) 
line, = axes1.plot(np.random.rand(10)) 
#因为update的参数是调用函数data_gen,
#所以第一个默认参数不能是framenum 
def update(data): 
  line.set_ydata(data) 
  return line, 
# 每次生成10个随机数据 
def data_gen(): 
  while True: 
    yield np.random.rand(10) 
ani = animation.FuncAnimation(fig, update, data_gen, interval=2*1000)
plt.show()

第二个例子使用list(metric),每次从metric中取一行数据作为参数送入update中:

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
start = [1, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0] 
metric =[[0.03, 0.86, 0.65, 0.34, 0.34, 0.02, 0.22, 0.74, 0.66, 0.65], 
     [0.43, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0.55], 
     [0.66, 0.75, 0.01, 0.94, 0.72, 0.77, 0.20, 0.66, 0.81, 0.52] 
    ] 
fig = plt.figure() 
window = fig.add_subplot(111) 
line, = window.plot(start) 
#如果是参数是list,则默认每次取list中的一个元素,
#即metric[0],metric[1],...
def update(data): 
  line.set_ydata(data) 
  return line, 
ani = animation.FuncAnimation(fig, update, metric, interval=2*1000) 
plt.show()

第三个例子:

import numpy as np 
from matplotlib import pyplot as plt 
from matplotlib import animation 
# First set up the figure, the axis, and the plot element we want to animate 
fig = plt.figure() 
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2)) 
line, = ax.plot([], [], lw=2) 
# initialization function: plot the background of each frame 
def init(): 
  line.set_data([], []) 
  return line, 
# animation function. This is called sequentially 
# note: i is framenumber 
def animate(i): 
  x = np.linspace(0, 2, 1000) 
  y = np.sin(2 * np.pi * (x - 0.01 * i)) 
  line.set_data(x, y) 
  return line, 
# call the animator. blit=True means only re-draw the parts that have changed. 
anim = animation.FuncAnimation(fig, animate, init_func=init, 
                frames=200, interval=20, blit=True) 
#anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264']) 
plt.show()

第四个例子:

# -*- coding: utf-8 -*- 
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
# 每次产生一个新的坐标点 
def data_gen(): 
  t = data_gen.t 
  cnt = 0 
  while cnt < 1000: 
    cnt+=1 
    t += 0.05 
    yield t, np.sin(2*np.pi*t) * np.exp(-t/10.) 
data_gen.t = 0 
# 绘图 
fig, ax = plt.subplots() 
line, = ax.plot([], [], lw=2) 
ax.set_ylim(-1.1, 1.1) 
ax.set_xlim(0, 5) 
ax.grid() 
xdata, ydata = [], [] 
# 因为run的参数是调用函数data_gen,
# 所以第一个参数可以不是framenum:设置line的数据,返回line 
def run(data): 
  # update the data 
  t,y = data 
  xdata.append(t) 
  ydata.append(y) 
  xmin, xmax = ax.get_xlim() 
  if t >= xmax: 
    ax.set_xlim(xmin, 2*xmax) 
    ax.figure.canvas.draw() 
  line.set_data(xdata, ydata) 
  return line, 
# 每隔10秒调用函数run,run的参数为函数data_gen, 
# 表示图形只更新需要绘制的元素 
ani = animation.FuncAnimation(fig, run, data_gen, blit=True, interval=10, 
  repeat=False) 
plt.show()

再看下面的例子:

# -*- coding: utf-8 -*- 
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
#第一个参数必须为framenum 
def update_line(num, data, line): 
  line.set_data(data[...,:num]) 
  return line, 
fig1 = plt.figure() 
data = np.random.rand(2, 15) 
l, = plt.plot([], [], 'r-') 
plt.xlim(0, 1) 
plt.ylim(0, 1) 
plt.xlabel('x') 
plt.title('test') 
#framenum从1增加大25后,返回再次从1增加到25,再返回... 
line_ani = animation.FuncAnimation(fig1, update_line, 25,fargs=(data, l),interval=50, blit=True) 
#等同于 
#line_ani = animation.FuncAnimation(fig1, update_line, frames=25,fargs=(data, l), 
#  interval=50, blit=True) 
#忽略frames参数,framenum会从1一直增加下去知道无穷 
#由于frame达到25以后,数据不再改变,所以你会发现到达25以后图形不再变化了 
#line_ani = animation.FuncAnimation(fig1, update_line, fargs=(data, l),
#  interval=50, blit=True) 
plt.show()

希望本文所述对大家的python程序设计有所帮助。

Python 相关文章推荐
使用Python编写一个最基础的代码解释器的要点解析
Jul 12 Python
Python函数的周期性执行实现方法
Aug 13 Python
基于Python socket的端口扫描程序实例代码
Feb 09 Python
python中format()函数的简单使用教程
Mar 14 Python
Python线程之定位与销毁的实现
Feb 17 Python
浅析Python3中的对象垃圾收集机制
Jun 06 Python
django如何实现视图重定向
Jul 24 Python
python实现邮件发送功能
Aug 10 Python
python getpass模块用法及实例详解
Oct 07 Python
Python使用urllib模块对URL网址中的中文编码与解码实例详解
Feb 18 Python
Python3创建Django项目的几种方法(3种)
Jun 03 Python
Python采集股票数据并制作可视化柱状图
Apr 04 Python
Python中subprocess模块用法实例详解
May 20 #Python
python检测某个变量是否有定义的方法
May 20 #Python
Python实现在matplotlib中两个坐标轴之间画一条直线光标的方法
May 20 #Python
python使用PyGame模块播放声音的方法
May 20 #Python
python实现带声音的摩斯码翻译实现方法
May 20 #Python
python定时检查某个进程是否已经关闭的方法
May 20 #Python
Python操作列表之List.insert()方法的使用
May 20 #Python
You might like
使用php测试硬盘写入速度示例
2014/01/27 PHP
thinkphp的URL路由规则与配置实例
2014/11/26 PHP
ThinkPHP框架结合Ajax实现用户名校验功能示例
2019/07/03 PHP
基于jquery的划词搜索实现(备忘)
2010/09/14 Javascript
模仿百度三维地图的js数据分享
2011/05/12 Javascript
jquery禁止输入数字以外的字符的示例(纯数字验证码)
2014/04/10 Javascript
jQuery中toggleClass()方法用法实例
2015/01/05 Javascript
JS+CSS实现的简单折叠展开多级菜单效果
2015/09/12 Javascript
对于js垃圾回收机制的理解
2017/09/14 Javascript
JS抛物线动画实例制作
2018/02/24 Javascript
Vue中Table组件Select的勾选和取消勾选事件详解
2019/03/19 Javascript
解决layui 表单元素radio不显示渲染的问题
2019/09/04 Javascript
基于javascript的无缝滚动动画1
2020/08/07 Javascript
[05:22]DOTA2 2015国际邀请赛中国区预选赛首日TOP10
2015/05/26 DOTA
在Python中移动目录结构的方法
2016/01/31 Python
Python 装饰器使用详解
2017/07/29 Python
ubuntu17.4下为python和python3装上pip的方法
2018/06/12 Python
TensorFlow实现iris数据集线性回归
2018/09/07 Python
PyCharm代码回滚,恢复历史版本的解决方法
2018/10/22 Python
利用Python实现Shp格式向GeoJSON的转换方法
2019/07/09 Python
python字符串分割及字符串的一些常规方法
2019/07/24 Python
Python流程控制 while循环实现解析
2019/09/02 Python
Pandas缺失值2种处理方式代码实例
2020/06/13 Python
使用Keras构造简单的CNN网络实例
2020/06/29 Python
tensorflow与numpy的版本兼容性问题的解决
2021/01/08 Python
用CSS3实现Win8风格的方格导航菜单效果
2013/04/10 HTML / CSS
波兰家居和花园家具专家:4Home
2019/05/26 全球购物
俄罗斯韩国化妆品网上商店:Cosmasi.ru
2019/10/31 全球购物
新西兰最大的天然保健及护肤品网站:HealthPost(直邮中国)
2021/02/13 全球购物
学校联谊活动方案
2014/02/15 职场文书
2014年维修工作总结
2014/11/22 职场文书
后勤个人工作总结
2015/02/28 职场文书
小学教学工作总结2015
2015/05/13 职场文书
党员转正党支部意见
2015/06/02 职场文书
2016年第32个教师节致辞
2015/11/26 职场文书
Win11 引入 Windows 365 云操作系统,适应疫情期间混合办公模式:启动时直接登录、模
2022/04/06 数码科技