{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n.. redirect-from:: /tutorials/introductory/animation_tutorial\n\n\n# Animations using Matplotlib\n\nBased on its plotting functionality, Matplotlib also provides an interface to\ngenerate animations using the `~matplotlib.animation` module. An\nanimation is a sequence of frames where each frame corresponds to a plot on a\n`~matplotlib.figure.Figure`. This tutorial covers a general guideline on\nhow to create such animations and the different options available. More information is available in the API description: `~matplotlib.animation`\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport matplotlib.animation as animation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Animation classes\n\nThe animation process in Matplotlib can be thought of in 2 different ways:\n\n- `~matplotlib.animation.FuncAnimation`: Generate data for first\n frame and then modify this data for each frame to create an animated plot.\n\n- `~matplotlib.animation.ArtistAnimation`: Generate a list (iterable)\n of artists that will draw in each frame in the animation.\n\n`~matplotlib.animation.FuncAnimation` is more efficient in terms of\nspeed and memory as it draws an artist once and then modifies it. On the\nother hand `~matplotlib.animation.ArtistAnimation` is flexible as it\nallows any iterable of artists to be animated in a sequence.\n\n### ``FuncAnimation``\n\nThe `~matplotlib.animation.FuncAnimation` class allows us to create an\nanimation by passing a function that iteratively modifies the data of a plot.\nThis is achieved by using the *setter* methods on various\n`~matplotlib.artist.Artist` (examples: `~matplotlib.lines.Line2D`,\n`~matplotlib.collections.PathCollection`, etc.). A usual\n`~matplotlib.animation.FuncAnimation` object takes a\n`~matplotlib.figure.Figure` that we want to animate and a function\n*func* that modifies the data plotted on the figure. It uses the *frames*\nparameter to determine the length of the animation. The *interval* parameter\nis used to determine time in milliseconds between drawing of two frames.\nAnimating using `.FuncAnimation` typically requires these steps:\n\n1) Plot the initial figure as you would in a static plot. Save all the created\n artists, which are returned by the plot functions, in variables so that you can\n access and modify them later in the animation function.\n2) Create an animation function that updates the artists for a given frame.\n Typically, this calls ``set_*`` methods of the artists.\n3) Create a `.FuncAnimation`, passing the `.Figure` and the animation function.\n4) Save or show the animation using one of the following methods:\n\n - `.pyplot.show` to show the animation in a window\n - `.Animation.to_html5_video` to create a HTML ``