数据可视化:matplotlib animation 绘制动画

1. 用 matplotlib animation 绘制动画

ref: https://matplotlib.org/3.1.1/api/animation_api.html

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
32
33
34
35
36
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np

# 数据集:X轴数据固定;Y轴的数据更新
X = np.arange(0, 10, 0.01) # X shape: (N,)
Ys = [np.sin(X + k / 10) for k in range(100)] # Ys shape: (k, N)


def my_ani(x, ys):
fig, ax = plt.subplots()
ax.set_title('y = sin(x + k/10)')
ax.set_xlim([0, 10]), ax.set_xlabel('X')
ax.set_ylim([-1, 1]), ax.set_ylabel('Y')

line, = ax.plot(x, ys[0])
ano = plt.annotate('k: 0', (1, 1))

def animate(i):
line.set_ydata(ys[i]) # update the y data.
ano.set_text('k: %d' % i) # update the annotate.
return line,

# animation.FuncAnimation 参数说明
# fig: figure 对象
# func: 动画函数,自定义函数 animate
# frames: 总帧数
# interval: 间隔时间,ms
ani = animation.FuncAnimation(fig, animate, frames=30, interval=50)
# ani.save('sin_ani.mp4', dpi=300, writer='ffmpeg') # scoop install ffmpeg
# ani.save('sin_ani.gif', dpi=300, writer='pillow') # pip install pillow
plt.show()


my_ani(X, Ys)

sin_ani.gif

2. 也用 plot 的方法显示动画,保存不太方便

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import matplotlib.pyplot as plt
import numpy as np

# 数据集:X轴数据固定;Y轴的数据更新
X = np.arange(0, 10, 0.01) # X shape: (N,)
Ys = [np.sin(X + k / 10) for k in range(100)] # Ys shape: (k, N)

plt.ion()
plt.show()
for i in range(len(Ys)):
plt.cla()

plt.title('y = sin(x + k/10)')
plt.xlim(0, 10)
plt.ylim(-1, 1)

plt.plot(X, Ys[i], 'r', alpha=0.7, linewidth=0.7)
plt.text(1, 1, 'k: %d' % i)

plt.draw()
plt.pause(0.05) # 间隔时间,s