这里介绍下,在matplotlib中绘制动画的一些方法,主要参考官方教程:http://matplotlib.org/api/animation_api.html
在matplotlib中制作活动画最简单的方法是使用一个动画类。
1.FuncAnimation
我们先来看FuncAnimation
class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, **kwargs)
Makes an animation by repeatedly calling a function func.
#要绘制的figure
fig : matplotlib.figure.Figure
The figure object that is used to get draw, resize, and any other needed events.
#回调函数
func : callable
#传递给func的参数
frames : iterable, int, generator function, or None, optional
小栗子
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig,axes = plt.subplots()
axes.plot(np.random.rand(10))
#重新绘制图形
def update_line(data):
#清空当前轴
plt.cla()
#重新绘图
axes.plot(data)
#生成绘制图形的数据
def create_line_data():
while True:
yield np.random.rand(10)
#传入的fig中,调用update_line函数,将create_line_data作为参数传给update_line,5秒调用一次
ani = animation.FuncAnimation(fig, update_line, create_line_data, interval=5*1000)
plt.show()
上面就简单的完成了一个简单的动画绘制,每5秒重新画一条线