matplotlib的基本用法(十六)——创建动画

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

本文主要介绍matplotlib的一些用法。

  • Demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation


# 定义figure
fig, ax = plt.subplots()

# 定义数据
x = np.arange(0, 2 * np.pi, 0.01)
# line, 表示只取返回值中的第一个元素
line, = ax.plot(x, np.sin(x))

# 定义动画的更新
def update(i):
line.set_ydata(np.sin(x + i/10))
return line,

# 定义动画的初始值
def init():
line.set_ydata(np.sin(x))
return line,

# 创建动画
ani = animation.FuncAnimation(fig = fig, func = update, init_func = init, interval = 10, blit = False, frames = 200)

# 展示动画
plt.show()

# 动画保存
ani.save('sin.gif', writer = 'imagemagick', fps = 30, dpi = 100)
  • 结果

图像

创建下雨的动画:

图像

参考资料

  1. https://www.youtube.com/user/MorvanZhou
如果有收获,可以请我喝杯咖啡!