Colab: How to use matplotlib animation in Colab?

Share:
# Problem: How to use animation inside Class member function in Colab? --- Colab 是谷歌开发的一款类似于Jupter notebook的编辑器,用Colab可以编写Python程序,进行深度学习相关的开发。 即使您的电脑上没有GPU,也可以利用此编辑器进行神经网络的训练。 当我尝试使用Coloab来写 《概率机器人 详解》这本书的程序时遇到了matplotlib animation 动画不能显示的问题。 本文示例将介绍一种方法来解决这个问题。 本文将介绍如何在Python的类中使用animation.FuncAnimation函数: ```sh anim = animation.FuncAnimation(self.fig, self.animate, init_func=self.init, frames=100, interval=100, blit=True) ``` 默认情况下,Colab是不显示动画的。 为了兼容Colab, 我采用的解决方案是: ```sh rc('animation', html='jshtml') anim ``` 将anim声明成全局变量,然后在程序末尾加上上述两句。 注: 如果animation.FuncAnimation不是在类成员函数中调用的话,也需要加上上述两名话。 --- Related modules: - matplotlib - Colab # Possible methods ```python from matplotlib import animation, rc # # other code # anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=100, blit=True) # below is the part which makes it work on Colab rc('animation', html='jshtml') anim # or HTML(anim.to_jshtml()) ``` However, how to use animation inside Class member function? Use **animation install** as globle variable. # Sample ```python import numpy as np import matplotlib.pyplot as plt from matplotlib import animation, rc from IPython.display import HTML class testAnimation: def __init__(self): # First set up the figure, the axis, and the plot element we want to animate self.fig, ax = plt.subplots() plt.close() ax.set_xlim(( 0, 2)) ax.set_ylim((-2, 2)) self.line, = ax.plot([], [], lw=2) # initialization function: plot the background of each frame def init(self): self.line.set_data([], []) return (self.line,) # animation function. This is called sequentially def animate(self, i): x = np.linspace(0, 2, 1000) y = np.sin(2 * np.pi * (x - 0.01 * i)) self.line.set_data(x, y) return (self.line,) def draw(self): global anim anim = animation.FuncAnimation(self.fig, self.animate, init_func=self.init, frames=100, interval=100, blit=True) vis = testAnimation() vis.draw() # Note: below is the part which makes it work on Colab rc('animation', html='jshtml') anim ``` # References - [korakot/animation.py](https://gist.github.com/korakot/b3c9b90d4f10dc3883c003697bf95bf4) - [matplotlib.animation.FuncAnimation](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.animation.FuncAnimation.html#matplotlib.animation.FuncAnimation) - [Colab animations.ipynb](https://colab.research.google.com/drive/1lnl5UPFWVPrryaZZgEzd0theI6S94c3X#scrollTo=QLRBwgFqdr83)

No comments