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的Django框架代码的一些示例
Apr 20 Python
Python实现对PPT文件进行截图操作的方法
Apr 28 Python
Python 3实战爬虫之爬取京东图书的图片详解
Oct 09 Python
Django项目中model的数据处理以及页面交互方法
May 30 Python
浅谈Pandas 排序之后索引的问题
Jun 07 Python
pyqt5 从本地选择图片 并显示在label上的实例
Jun 13 Python
解决python中的幂函数、指数函数问题
Nov 25 Python
基于python图像处理API的使用示例
Apr 03 Python
解决windows上安装tensorflow时报错,“DLL load failed: 找不到指定的模块”的问题
May 20 Python
Pytorch转keras的有效方法,以FlowNet为例讲解
May 26 Python
使用Python实现音频双通道分离
Dec 25 Python
Python中for后接else的语法使用
May 18 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设计模式中的工厂模式
2008/06/12 PHP
PHP simple_html_dom.php+正则 采集文章代码
2009/12/24 PHP
Views rows style模板重写代码
2011/05/16 PHP
PHP无限分类代码,支持数组格式化、直接输出菜单两种方式
2011/05/18 PHP
PHP查询网站的PR值
2013/10/30 PHP
WordPress中重置文章循环的rewind_posts()函数讲解
2016/01/11 PHP
一个对于Array的简单扩展
2006/10/03 Javascript
使用Jquery Aajx访问WCF服务(GET、POST、PUT、DELETE)
2012/03/16 Javascript
JS判断文本框内容改变事件的简单实例
2014/03/07 Javascript
动态载入js提高网页打开速度的方法
2014/07/04 Javascript
javascript使用window.open提示“已经计划系统关机”的原因
2014/08/15 Javascript
5个可以帮你理解JavaScript核心闭包和作用域的小例子
2014/10/08 Javascript
jQuery幻灯片特效代码分享--鼠标滑过按钮时切换(2)
2020/11/18 Javascript
一步一步封装自己的HtmlHelper组件BootstrapHelper(二)
2016/09/14 Javascript
vue综合组件间的通信详解
2017/11/06 Javascript
Vue.js中 v-model 指令的修饰符详解
2018/12/03 Javascript
node.js的Express服务器基本使用教程
2019/01/09 Javascript
详解Vue中使用Axios拦截器
2019/04/22 Javascript
jquery实现Ajax请求的几种常见方式总结
2019/05/28 jQuery
在Python程序和Flask框架中使用SQLAlchemy的教程
2016/06/06 Python
Python网络编程 Python套接字编程
2017/09/13 Python
解决django前后端分离csrf验证的问题
2019/02/03 Python
Python制作词云图代码实例
2019/09/09 Python
pytorch GAN生成对抗网络实例
2020/01/10 Python
django admin 添加自定义链接方式
2020/03/11 Python
css图标制作教程制作云图标
2014/01/19 HTML / CSS
企业面试题试卷附带答案
2015/12/20 面试题
学期自我评价
2014/01/27 职场文书
教师产假请假条
2014/04/10 职场文书
交通事故调解协议书
2014/04/16 职场文书
小学生教师节演讲稿
2014/09/03 职场文书
辞职信格式模板
2015/02/27 职场文书
起诉书格式范文
2015/05/20 职场文书
如何书写邀请函?
2019/06/24 职场文书
用golang如何替换某个文件中的字符串
2021/04/25 Golang
Python 数据可视化神器Pyecharts绘制图像练习
2022/02/28 Python