Matplotlib animation模块实现动态图


Posted in Python onFebruary 25, 2021

matplotlib 画图功能非常强大,目前也只能根据官网 提供的例子简单地画几张图。最近学习了能画动态图的animation模块,作个简单地记录。

在matplotlib作图中,比较常用的是matplotlib.pyplot模块,这个模块有非常多的属性和方法,简要列举下这次用到的方法:
matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)
返回fig和ax对象!

例子1. 动态画出sin函数曲线

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = ax.plot([], [], 'r-', animated=False)

def init():
  ax.set_xlim(0, 2*np.pi)
  ax.set_ylim(-1, 1)
  return ln,

def update(frame):
  xdata.append(frame)
  ydata.append(np.sin(frame))
  ln.set_data(xdata, ydata)
  return ln,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
          init_func=init, blit=True)
plt.show()

Matplotlib animation模块实现动态图

画这类图的关键是要给出不断更新的函数,这里就是update 函数了。注意, line, = ax.plot([], [], 'r-', animated=False) 中的, 表示创建tuple类型。迭代更新的数据frame 取值从frames 取得。

例子2. 动态显示一个动点,它的轨迹是sin函数。

import numpy as np 
import matplotlib.pyplot as plt
from matplotlib import animation

"""
animation example 2
author: Kiterun
"""

fig, ax = plt.subplots()
x = np.linspace(0, 2*np.pi, 200)
y = np.sin(x)
l = ax.plot(x, y)
dot, = ax.plot([], [], 'ro')

def init():
  ax.set_xlim(0, 2*np.pi)
  ax.set_ylim(-1, 1)
  return l

def gen_dot():
  for i in np.linspace(0, 2*np.pi, 200):
    newdot = [i, np.sin(i)]
    yield newdot

def update_dot(newd):
  dot.set_data(newd[0], newd[1])
  return dot,

ani = animation.FuncAnimation(fig, update_dot, frames = gen_dot, interval = 100, init_func=init)
ani.save('sin_dot.gif', writer='imagemagick', fps=30)

plt.show()

这里我们把生成的动态图保存为gif图片,前提要预先安装imagemagic。

Matplotlib animation模块实现动态图

例子3. 单摆(没阻尼&有阻尼)

无阻尼的单摆力学公式:

Matplotlib animation模块实现动态图

附加阻尼项:

Matplotlib animation模块实现动态图

这里需要用到scipy.integrate的odeint模块,具体用法找时间再专门写一篇blog吧,动态图代码如下:

# -*- coding: utf-8 -*-

from math import sin, cos
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import matplotlib.animation as animation

g = 9.8
leng = 1.0
b_const = 0.2

# no decay case:
def pendulum_equations1(w, t, l):
  th, v = w
  dth = v
  dv = - g/l * sin(th)
  return dth, dv

# the decay exist case:
def pendulum_equations2(w, t, l, b):
  th, v = w
  dth = v
  dv = -b/l * v - g/l * sin(th)
  return dth, dv

t = np.arange(0, 20, 0.1)
track = odeint(pendulum_equations1, (1.0, 0), t, args=(leng,))
#track = odeint(pendulum_equations2, (1.0, 0), t, args=(leng, b_const))
xdata = [leng*sin(track[i, 0]) for i in range(len(track))]
ydata = [-leng*cos(track[i, 0]) for i in range(len(track))]

fig, ax = plt.subplots()
ax.grid()
line, = ax.plot([], [], 'o-', lw=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)

def init():
  ax.set_xlim(-2, 2)
  ax.set_ylim(-2, 2)
  time_text.set_text('')
  return line, time_text

def update(i):
  newx = [0, xdata[i]]
  newy = [0, ydata[i]]
  line.set_data(newx, newy)
  time_text.set_text(time_template %(0.1*i))
  return line, time_text

ani = animation.FuncAnimation(fig, update, range(1, len(xdata)), init_func=init, interval=50)
#ani.save('single_pendulum_decay.gif', writer='imagemagick', fps=100)
ani.save('single_pendulum_nodecay.gif', writer='imagemagick', fps=100)
plt.show()

Matplotlib animation模块实现动态图 

Matplotlib animation模块实现动态图

例子4. 滚动的球

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation

fig = plt.figure(figsize=(6, 6))
ax = plt.gca()
ax.grid()
ln1, = ax.plot([], [], '-', lw=2)
ln2, = ax.plot([], [], '-', color='r', lw=2)
theta = np.linspace(0, 2*np.pi, 100)
r_out = 1
r_in = 0.5

def init():
  ax.set_xlim(-2, 2)
  ax.set_ylim(-2, 2)
  x_out = [r_out*np.cos(theta[i]) for i in range(len(theta))]
  y_out = [r_out*np.sin(theta[i]) for i in range(len(theta))]
  ln1.set_data(x_out, y_out)
  return ln1,

def update(i):
  x_in = [(r_out-r_in)*np.cos(theta[i])+r_in*np.cos(theta[j]) for j in range(len(theta))]
  y_in = [(r_out-r_in)*np.sin(theta[i])+r_in*np.sin(theta[j]) for j in range(len(theta))]
  ln2.set_data(x_in, y_in)
  return ln2,

ani = animation.FuncAnimation(fig, update, range(len(theta)), init_func=init, interval=30)
ani.save('roll.gif', writer='imagemagick', fps=100)

plt.show()

Matplotlib animation模块实现动态图

到此这篇关于Matplotlib animation模块实现动态图 的文章就介绍到这了,更多相关Matplotlib 动态图 内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python实现对比不同字体中的同一字符的显示效果
Apr 23 Python
python使用xlrd模块读写Excel文件的方法
May 06 Python
Python实现简单登录验证
Apr 13 Python
Python实现将一个大文件按段落分隔为多个小文件的简单操作方法
Apr 17 Python
解决python3爬虫无法显示中文的问题
Apr 12 Python
解决pyinstaller打包发布后的exe文件打开控制台闪退的问题
Jun 21 Python
Python实现平行坐标图的绘制(plotly)方式
Nov 22 Python
python 使用三引号时容易犯的小错误
Oct 21 Python
最新Python idle下载、安装与使用教程图文详解
Nov 28 Python
解决Pytorch修改预训练模型时遇到key不匹配的情况
Jun 05 Python
Python 快速验证代理IP是否有效的方法实现
Jul 15 Python
python3操作redis实现List列表实例
Aug 04 Python
python连接手机自动搜集蚂蚁森林能量的实现代码
Feb 24 #Python
Python爬取你好李焕英豆瓣短评生成词云的示例代码
Feb 24 #Python
用pip给python安装matplotlib库的详细教程
Feb 24 #Python
matplotlib 范围选区(SpanSelector)的使用
Feb 24 #Python
matplotlib之多边形选区(PolygonSelector)的使用
Feb 24 #Python
matplotlib部件之套索Lasso的使用
Feb 24 #Python
matplotlib之属性组合包(cycler)的使用
Feb 24 #Python
You might like
php.ini中date.timezone设置分析
2011/07/29 PHP
php操作mysqli(示例代码)
2013/10/28 PHP
php自定义扩展名获取函数示例
2016/12/12 PHP
Laravel5.* 打印出执行的sql语句的方法
2017/07/24 PHP
Firefox中beforeunload事件的实现缺陷浅析
2012/05/03 Javascript
基于jquery创建的一个图片、视频缓冲的效果样式插件
2012/08/28 Javascript
复选框全选与全不选操作实现思路
2013/08/18 Javascript
jquery给图片添加鼠标经过时的边框效果
2013/11/12 Javascript
举例讲解JavaScript中将数组元素转换为字符串的方法
2015/10/25 Javascript
JavaScript与jQuery实现的闪烁输入效果
2016/02/18 Javascript
AngularJS基础 ng-non-bindable 指令详细介绍
2016/08/02 Javascript
详解微信小程序Page中data数据操作和函数调用
2017/09/27 Javascript
微信小程序里引入SVG矢量图标的方法
2019/09/20 Javascript
使用JavaScript获取扫码枪扫描得到的条形码的思路代码详解
2020/06/10 Javascript
JS的时间格式化和时间戳转换函数示例详解
2020/07/27 Javascript
[00:32]2018DOTA2亚洲邀请赛iG出场
2018/04/03 DOTA
[46:59]完美世界DOTA2联赛PWL S2 GXR vs Ink 第二场 11.19
2020/11/20 DOTA
[03:13]DOTA2-DPC中国联赛1月25日Recap集锦
2021/03/11 DOTA
django表单实现下拉框的示例讲解
2018/05/29 Python
谈一谈基于python的面向对象编程基础
2019/05/21 Python
使用WingPro 7 设置Python路径的方法
2019/07/24 Python
Python 余弦相似度与皮尔逊相关系数 计算实例
2019/12/23 Python
如何使用selenium和requests组合实现登录页面
2020/02/03 Python
Python3爬虫中关于Ajax分析方法的总结
2020/07/10 Python
纯HTML5+CSS3制作生日蛋糕(代码易懂)
2016/11/16 HTML / CSS
世界知名接发和假发品牌:Poze Hair
2017/03/08 全球购物
护士自荐信怎么写
2013/10/18 职场文书
季度思想汇报
2014/01/01 职场文书
人事助理自荐信
2014/02/02 职场文书
铁路工务反思材料
2014/02/07 职场文书
党的群众路线教育实践活动批评与自我批评
2014/02/16 职场文书
开学典礼策划方案
2014/05/28 职场文书
听课评课活动心得体会
2016/01/15 职场文书
导游词之台湾阿里山
2019/10/23 职场文书
Redis延迟队列和分布式延迟队列的简答实现
2021/05/13 Redis
python利用while求100内的整数和方式
2021/11/07 Python