Last active
August 29, 2015 13:56
-
-
Save edrex/9044756 to your computer and use it in GitHub Desktop.
matplotlib animations as HTML5 video
This file contains 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
{ | |
"metadata": { | |
"name": "" | |
}, | |
"nbformat": 3, | |
"nbformat_minor": 0, | |
"worksheets": [ | |
{ | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"# Display matplotlib animations as HTML5 video\n", | |
"\n", | |
"Based on [this notebook](http://nbviewer.ipython.org/url/jakevdp.github.io/downloads/notebooks/AnimationEmbedding.ipynb) by jakevdp. Updated with:\n", | |
"\n", | |
" - output video that works with chrome (pix_fmt below)\n", | |
" - add plt.close() to avoid showing PNG below the animation\n", | |
" - autoplay (customize the VIDEO_TAG below to change behavior, for example add loop attribute)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"from matplotlib import animation, pyplot as plt\n", | |
"from tempfile import NamedTemporaryFile\n", | |
"\n", | |
"VIDEO_TAG = \"\"\"<video controls autoplay>\n", | |
" <source src=\"data:{0}\">\n", | |
" Your browser does not support the video tag.\n", | |
"</video>\"\"\"\n", | |
"\n", | |
"def anim_to_html(anim):\n", | |
" if not hasattr(anim, '_encoded_video'):\n", | |
" with NamedTemporaryFile(suffix='.m4v') as f:\n", | |
" anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264', '-pix_fmt', 'yuv420p'])\n", | |
" video = open(f.name, \"rb\").read()\n", | |
" anim._encoded_video = 'video/mp4;base64,' + video.encode(\"base64\")\n", | |
" # prevent figure displayed as a PNG below the animation\n", | |
" plt.close()\n", | |
" \n", | |
" return VIDEO_TAG.format(anim._encoded_video)\n", | |
"\n", | |
"animation.Animation._repr_html_ = anim_to_html" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [], | |
"prompt_number": 20 | |
} | |
], | |
"metadata": {} | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment