Python中的matplotlib从1.1.0版本以后就开始支持绘制动画,Matplotlib 是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形。这里介绍几种Python使用matplotlib绘制动画的方法。

下面是几个的示例:

第一个例子使用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

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绘制几个动画相关推荐

  1. python函数复用_【python学习-4】可复用函数与模块

    1.自定义函数 自定义函数格式如下: def (参数列表):return #!/usr/bin/python#定义函数,打印数字1~5 defprintNum5():#range函数,生成列表集合,有 ...

  2. python函数示例_带Python示例的complex()函数

    python函数示例 Python complex()函数 (Python complex() function) complex() function is a library function i ...

  3. python函数实例化_用Python实例化函数

    python函数实例化 In terms of Mathematics and Computer science, currying is the approach/technique by whic ...

  4. python函数示例_带Python示例的float()函数

    python函数示例 Python float()函数 (Python float() function) float() function is a library function in Pyth ...

  5. python函数示例_使用Python中的示例的input()函数

    python函数示例 Python input()函数 (Python input() function) input() function is a library function, it is ...

  6. python函数转换_将Python函数转换为PL/Python函数

    我编写了几个python函数来对数据集中的连续变量进行幂变换.第一个函数基本上查找每个列的数据类型,并返回数据类型的dict以及相应的列名称作为值.在 第二个函数现在接受数据类型和列名的dict,并获 ...

  7. python 函数重载_在Python中实现函数重载,60%的人都不会

    connect('123.45.32.18:8080') connect(('123.45.32.18', 8080)) 复制代码 你想在代码里面兼容这两种写法,于是你可能会这样写代码: def co ...

  8. python函数笔记_初学Python函数的笔记整理

    定义 返回单值 def my_abs(x): if x >= 0: return x else: return -x 返回多值 返回多值就是返回一个tuple import math def m ...

  9. python 时间序列预测_使用Python进行动手时间序列预测

    python 时间序列预测 Time series analysis is the endeavor of extracting meaningful summary and statistical ...

  10. Python 函数声明和调用 - Python零基础入门教程

    目录 一.前言 二.Python 函数定义 三.Python 函数的调用 四.Python 函数传参 1.Python 函数常规参数 2.Python 函数缺省参数 3.Python 函数不定长参数 ...

最新文章

  1. 微信小程序之圆形进度条(自定义组件)
  2. SSM中抛出异常 java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoad
  3. 微软把UWP定位成业务线应用程序开发平台
  4. 排序算法之冒泡排序,选择排序
  5. String类、StringBuffer类、StringBuilder类的区别
  6. 实现option上下移动_Django实战2-自动化运维之配置管理-05:字典管理功能实现
  7. 接口自动化测试(Python+Requests+Unittest)
  8. 第九章 深度强化学习-Double DQN
  9. word刷子刷格式_Word文档中用格式刷快速编辑数据格式的方法
  10. Linux学习笔记-shell脚本-log脚本函数
  11. 如何防止企业电子邮件外泄
  12. 关于使用硬盘对拷机后两硬盘UUID一样无法挂载问题
  13. 【日常技巧】小米手机投屏至win10笔记本
  14. 计算机关闭后剪切板的内容会消失,清除win10剪贴板历史记录,保证隐私数据不泄露...
  15. 为何买了专业设备又要卖掉?怎样正确自学拍摄、剪辑做视频?
  16. 主流链分片技术和共识算法
  17. English Grammer-01
  18. shapefile格式(援引)
  19. 低代码助力生产管理:ERP生产管理系统
  20. 烘焙贴图(二)——展UV

热门文章

  1. JAVA HttpClient 图片下载不全(坑点笔记)
  2. 谷歌浏览器ajax脚本出错,你好,用谷歌浏览器,发生脚本错误怎么处理。
  3. SDCC讲师预热专访:淘宝岑文初谈开放平台架构
  4. 【干货】NTP时间同步服务器技术详解
  5. 中国家庭医生签约服务基地项目在杭州启动
  6. mysql防注入插件_MyBB HM_My Country Flags 插件'cnam'参数SQL注入漏洞
  7. C++ Qt C#文件夹重命名 C#复制文件(夹)
  8. 电动汽车单轮驱动防滑控制系统ASR
  9. jQuery实现网页聊天窗口对话
  10. 阿里云ACE改革后难度变大了,还有人考吗?划不划算?