1 原理
- 生成图片容器
- 绘制坐标轴
- 绘制初始页面
- 绘制每帧图像
- 生成动画
绘制动画和以前放映电影一样,需要有一幅幅图像,然后动起来就称为了动画。每一幅图像就是一帧。
matplotlib自带有动画函数animation()。animation()含有六个参数,填写六个参数的过程就是生产动画的过程。 - 第一个参数,指明用的是哪个绘图容器;
- 第二个参数,指明动画如何动;
- 第三个参数,指明初始状态;
- 第四个参数,一共有多少帧;
- 第五个参数,指明每帧之间的时间间隔;
- 第六个参数,填写False即可。
绘制过程
#-*- coding:utf-8 -*-
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.animation import FFMpegWriter
#建立一个图片
fig = plt.figure()
#建立一个坐标轴,并且规定坐标的取值范围
ax = plt.axes(xlim=(0,2*np.pi),ylim=(-1,1))
x =np.arange(0,2*np.pi,0.05)
y =np.sin(x)
ln, = plt.plot(x,y)
#绘制图像
def init():
#ln, = plt.plot(x,y)
return ln
def update(frame):
y =np.sin(x+frame)
ln.set_ydata(y)
return ln
anim = animation.FuncAnimation(fig, update, init_func=init,
frames=5, interval=500, blit=False)
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264']) #输出视频格式文件,需要安装ffmpeg。
anim.save('sin_test2.gif', writer='imagemagick', fps=30)#保存为动画格式
plt.show()

sin_test2.gif
https://blog.csdn.net/briblue/article/details/84940997
ffmpeg安装
动画例子