{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2D animation\n\nThis example demonstrates how matplotlib can be used to create \nanimated movie and export these in the mp4 movie format. \n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nfig, ax = plt.subplots()\n\n\ndef f(x, y):\n return np.sin(x) + np.cos(y)\n\n\nx = np.linspace(0, 2 * np.pi, 120)\ny = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)\n\n# ims is a list of lists, each row is a list of artists to draw in the\n# current frame; here we are just animating one artist, the image, in\n# each frame\nims = []\nfor i in range(60):\n x += np.pi / 15.0\n y += np.pi / 20.0\n im = ax.imshow(f(x, y), animated=True)\n if i == 0:\n ax.imshow(f(x, y)) # show an initial one first\n ims.append([im])\n\nani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=1000)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To save the animation, use e.g.\n\n```python\nani.save(\"movie.mp4\")\n```\nor\n\n```python\nwriter = animation.FFMpegWriter(\nfps=15, metadata=dict(artist='Me'), bitrate=1800)\nani.save(\"movie.mp4\", writer=writer)\n```\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.10" } }, "nbformat": 4, "nbformat_minor": 0 }