Created
February 25, 2018 00:15
-
-
Save clintval/73837eff50a6b6fd42be6fa2c39f441f to your computer and use it in GitHub Desktop.
Matplotlib Animation in Notebook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import base64 | |
| import matplotlib.pyplot as plt | |
| from matplotlib import animation | |
| from tempfile import NamedTemporaryFile | |
| __all__ = [ | |
| 'Animation', | |
| 'animate_3d_scatter'] | |
| VIDEO_TAG = """<video controls> | |
| <source src="data:video/x-m4v;base64,{0}" type="video/mp4"> | |
| Your browser does not support the video tag. | |
| </video>""" | |
| class Animation(animation.Animation): | |
| def __init__(self): | |
| super().__init__() | |
| def _repr_html(self): | |
| if not hasattr(self, '_encoded_video'): | |
| with NamedTemporaryFile(suffix='.mp4') as f: | |
| self.save( | |
| f.name, | |
| fps=20, | |
| extra_args=['-vcodec', 'libx264', '-pix_fmt', 'yuv420p']) | |
| video = open(f.name, 'rb').read() | |
| self._encoded_video = base64.b64encode(video).decode('utf-8') | |
| return VIDEO_TAG.format(self._encoded_video) | |
| def animate_3d_scatter(fig, points, frames=730, interval=0.5, blit=True): | |
| def animate(i): | |
| plt.gca().view_init(30, i) | |
| return points, | |
| anim = animation.FuncAnimation( | |
| fig, | |
| animate, | |
| init_func=lambda: points, | |
| frames=360 * 2, | |
| interval=0.5, | |
| blit=True) | |
| return anim |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment