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改变日志(logging)存放位置的示例
Mar 27 Python
Python的subprocess模块总结
Nov 07 Python
Python字符编码判断方法分析
Jul 01 Python
听歌识曲--用python实现一个音乐检索器的功能
Nov 15 Python
遗传算法之Python实现代码
Oct 10 Python
在Python中字典根据多项规则排序的方法
Jan 21 Python
matlab中imadjust函数的作用及应用举例
Feb 27 Python
Python调用ffmpeg开源视频处理库,批量处理视频
Nov 16 Python
如何通过python检查文件是否被占用
Dec 18 Python
手把手教你用Django执行原生SQL的方法
Feb 18 Python
详解python的xlwings库读写excel操作总结
Feb 26 Python
Python制作春联的示例代码
Jan 22 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
PHP4在Windows2000下的安装
2006/10/09 PHP
Laravel 4 初级教程之视图、命名空间、路由
2014/10/30 PHP
php针对cookie操作的队列操作类实例
2014/12/10 PHP
php官方微信接口大全(微信支付、微信红包、微信摇一摇、微信小店)
2015/12/21 PHP
总结PHP中DateTime的常用方法
2016/08/11 PHP
PHP空值检测函数与方法汇总
2017/11/19 PHP
PHP7下协程的实现方法详解
2017/12/17 PHP
PHP进阶学习之类的自动加载机制原理分析
2019/06/18 PHP
PHP数组array类常见操作示例
2020/05/15 PHP
自写简单JS判断是否已经弹出页面
2010/10/20 Javascript
js绑定事件this指向发生改变的问题解决方法
2013/04/23 Javascript
jQuery操作CheckBox的方法介绍(选中,取消,取值)
2014/02/04 Javascript
复制网页内容,粘贴之后自动加上网址的实现方法(脚本之家特别整理)
2014/10/16 Javascript
jquery+javascript编写国籍控件
2015/02/12 Javascript
超实用的JavaScript表单代码段
2016/02/26 Javascript
Node.js实现数据推送
2016/04/14 Javascript
AngularJS中的promise用法分析
2017/05/19 Javascript
webpack下实现动态引入文件方法
2018/02/22 Javascript
Vue不能检测到Object/Array更新的情况的解决
2018/06/26 Javascript
使用Javascript简单计算器
2018/11/17 Javascript
基于Fixed定位的框选功能的实现代码
2019/05/13 Javascript
详解如何在vue+element-ui的项目中封装dialog组件
2020/12/11 Vue.js
[11:57]《一刀刀一天》第十七期:TI中国军团加油!
2014/05/26 DOTA
python将每个单词按空格分开并保存到文件中
2018/03/19 Python
Python3.6日志Logging模块简单用法示例
2018/06/14 Python
使用Fabric自动化部署Django项目的实现
2019/09/27 Python
python 成功引入包但无法正常调用的解决
2020/03/09 Python
使用placeholder属性设置input文本框的提示信息
2020/02/19 HTML / CSS
德国领先的大尺码和超大尺码男装在线零售商:Bigtex
2019/06/22 全球购物
物业保安员岗位职责制度
2014/01/30 职场文书
幼儿园社区活动总结
2014/07/07 职场文书
法人授权委托书
2014/09/16 职场文书
班主任高考寄语
2015/02/26 职场文书
农村老人去世追悼词
2015/06/23 职场文书
2017春节晚会开幕词
2016/03/03 职场文书
Python基础知识之变量的详解
2021/04/14 Python