##### 作者 Navjot 王小新 编译自 TowardsDataScience 量子位 出品 | 公众号 QbitAI

Jupyter Notebooks中，可以很容易地运行`matplotlib`库中的动图接口，但Colab中，就需要开动脑筋。

```from matplotlib import rc
rc('animation', html='jshtml')```

```import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation```

```x = np.linspace(-4, 4, 100)
y = np.sin(x)```

```fig, ax = plt.subplots()
ax.set_xlim(( -4, 4))
ax.set_ylim((-2, 2))```

```line1, = ax.plot([], [], lw=2)
line2, = ax.plot([], [], lw=2)```

```def init():
line1.set_data(x, y)
return (line1,)```

```def animate(i):
at_x = x[i]

# gradient_line will have the form m*x + b
m = np.cos(at_x)
b = np.sin(at_x) - np.cos(at_x)*at_x

return (line2,)```

`anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=100, blit=True)`

`rc('animation', html='jshtml')`

```import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation, rc
from IPython.display import HTML

# animate over some set of x, y
x = np.linspace(-4, 4, 100)
y = np.sin(x)

# First set up the figure, the axes, and the plot element
fig, ax = plt.subplots()
plt.close()
ax.set_xlim(( -4, 4))
ax.set_ylim((-2, 2))

line1, = ax.plot([], [], lw=2)
line2, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
line1.set_data(x, y)
return (line1,)

# animation function: this is called sequentially
def animate(i):
at_x = x[i]

# gradient_line will have the form m*x + b
m = np.cos(at_x)
b = np.sin(at_x) - np.cos(at_x)*at_x

return (line2,)

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=100, blit=True)
rc('animation', html='jshtml')
anim```

1. 本文的配套Colab文档：

2. 动图内嵌为交互式JavaScript小部件的方法：

http://tiao.io/posts/notebooks/embedding-matplotlib-animations-in-jupyter-as-interactive-javascript-widgets/

3. 原文：

3622 篇文章110 人订阅

0 条评论

21650

13220

577110

36980

12030

31220

28250

25730

14850

284100