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

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

matplotlib animation 动画教程都是针对曲线类型的,

对于包含子图、或含有类似直方图等图形的情况,就不适用了。

下面尝试实现包含多个子图,同时有直方图的动画效果。

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


X = np.arange(0, 10, 0.01) # X shape: (N,)
Ys = [np.sin(X + k/10.0) for k in range(100)] # Ys shape: (k, N)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(8, 4))

def animate(i):
axes[0].cla()
axes[0].plot(X, Ys[i])
axes[0].set_title(f'y = sin(x + {i}/10)')

axes[1].cla()
axes[1].hist(Ys[i], bins=50, orientation='horizontal')

ani = animation.FuncAnimation(fig, animate, frames=50, interval=50)
ani.save('matplotlib-animation-hist.gif')
plt.show()

ani.gif

ok!