{
  "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 an HTML ``<video>`` tag\n   - `.Animation.to_jshtml` to create HTML code with interactive JavaScript animation\n     controls\n   - `.Animation.save` to save the animation to a file\n\nThe following table shows a few plotting methods, the artists they return and some\ncommonly used ``set_*`` methods that update the underlying data. While updating data\nis the most common operation in animations, you can also update other aspects such as\ncolor or text position.\n\n========================================  =============================  ===========================\nPlotting method                           Artist                         Data set methods\n========================================  =============================  ===========================\n`.Axes.plot`                              `.lines.Line2D`                `~.Line2D.set_data`,\n                                                                         `~.Line2D.set_xdata`,\n                                                                         `~.Line2D.set_ydata`\n`.Axes.scatter`                           `.collections.PathCollection`  `~.collections.\\\n                                                                         PathCollection.set_offsets`\n`.Axes.imshow`                            `.image.AxesImage`             ``AxesImage.set_data``\n`.Axes.annotate`                          `.text.Annotation`             `~.text.Annotation.\\\n                                                                         update_positions`\n`.Axes.barh`                              `.patches.Rectangle`           `~.Rectangle.set_angle`,\n                                                                         `~.Rectangle.set_bounds`,\n                                                                         `~.Rectangle.set_height`,\n                                                                         `~.Rectangle.set_width`,\n                                                                         `~.Rectangle.set_x`,\n                                                                         `~.Rectangle.set_y`,\n                                                                         `~.Rectangle.set_xy`\n`.Axes.fill`                              `.patches.Polygon`             `~.Polygon.set_xy`\n`.Axes.add_patch`\\(`.patches.Ellipse`\\)   `.patches.Ellipse`             `~.Ellipse.set_angle`,\n                                                                         `~.Ellipse.set_center`,\n                                                                         `~.Ellipse.set_height`,\n                                                                         `~.Ellipse.set_width`\n`.Axes.set_title`, `.Axes.text`           `.text.Text`                   `~.Text.set_text`\n========================================  =============================  ===========================\n\nCovering the set methods for all types of artists is beyond the scope of this\ntutorial but can be found in their respective documentations. An example of\nsuch update methods in use for `.Axes.scatter` and `.Axes.plot` is as follows.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, ax = plt.subplots()\nt = np.linspace(0, 3, 40)\ng = -9.81\nv0 = 12\nz = g * t**2 / 2 + v0 * t\n\nv02 = 5\nz2 = g * t**2 / 2 + v02 * t\n\nscat = ax.scatter(t[0], z[0], c=\"b\", s=5, label=f'v0 = {v0} m/s')\nline2 = ax.plot(t[0], z2[0], label=f'v0 = {v02} m/s')[0]\nax.set(xlim=(0, 3), ylim=(-4, 10), xlabel='Time [s]', ylabel='Z [m]')\nax.legend()\n\n\ndef update(frame):\n    # for each frame, update the data stored on each artist.\n    x = t[:frame]\n    y = z[:frame]\n    # update the scatter plot:\n    data = np.stack([x, y]).T\n    scat.set_offsets(data)\n    # update the line plot:\n    line2.set_xdata(t[:frame])\n    line2.set_ydata(z2[:frame])\n    return (scat, line2)\n\n\nani = animation.FuncAnimation(fig=fig, func=update, frames=40, interval=30)\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### ``ArtistAnimation``\n\n`~matplotlib.animation.ArtistAnimation` can be used\nto generate animations if there is data stored on various different artists.\nThis list of artists is then converted frame by frame into an animation. For\nexample, when we use `.Axes.barh` to plot a bar-chart, it creates a number of\nartists for each of the bar and error bars. To update the plot, one would\nneed to update each of the bars from the container individually and redraw\nthem. Instead, `.animation.ArtistAnimation` can be used to plot each frame\nindividually and then stitched together to form an animation. A barchart race\nis a simple example for this.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, ax = plt.subplots()\nrng = np.random.default_rng(19680801)\ndata = np.array([20, 20, 20, 20])\nx = np.array([1, 2, 3, 4])\n\nartists = []\ncolors = ['tab:blue', 'tab:red', 'tab:green', 'tab:purple']\nfor i in range(20):\n    data += rng.integers(low=0, high=10, size=data.shape)\n    container = ax.barh(x, data, color=colors)\n    artists.append(container)\n\n\nani = animation.ArtistAnimation(fig=fig, artists=artists, interval=400)\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Animation writers\n\nAnimation objects can be saved to disk using various multimedia writers\n(ex: Pillow, *ffpmeg*, *imagemagick*). Not all video formats are supported\nby all writers. There are 4 major types of writers:\n\n- `~matplotlib.animation.PillowWriter` - Uses the Pillow library to\n  create the animation.\n\n- `~matplotlib.animation.HTMLWriter` - Used to create JavaScript-based\n  animations.\n\n- Pipe-based writers - `~matplotlib.animation.FFMpegWriter` and\n  `~matplotlib.animation.ImageMagickWriter` are pipe based writers.\n  These writers pipe each frame to the utility (*ffmpeg* / *imagemagick*)\n  which then stitches all of them together to create the animation.\n\n- File-based writers - `~matplotlib.animation.FFMpegFileWriter` and\n  `~matplotlib.animation.ImageMagickFileWriter` are examples of\n  file-based writers. These writers are slower than their pipe-based\n  alternatives but are more useful for debugging as they save each frame in\n  a file before stitching them together into an animation.\n\n### Saving Animations\n\n.. list-table::\n   :header-rows: 1\n\n   * - Writer\n     - Supported Formats\n   * - `~matplotlib.animation.PillowWriter`\n     - .gif, .apng, .webp\n   * - `~matplotlib.animation.HTMLWriter`\n     - .htm, .html, .png\n   * - | `~matplotlib.animation.FFMpegWriter`\n       | `~matplotlib.animation.FFMpegFileWriter`\n     - All formats supported by |ffmpeg|_: ``ffmpeg -formats``\n   * - | `~matplotlib.animation.ImageMagickWriter`\n       | `~matplotlib.animation.ImageMagickFileWriter`\n     - All formats supported by |imagemagick|_: ``magick -list format``\n\n.. |ffmpeg| replace:: *ffmpeg*\n\n.. |imagemagick| replace:: *imagemagick*\n\nTo save animations using any of the writers, we can use the\n`.animation.Animation.save` method. It takes the *filename* that we want to\nsave the animation as and the *writer*, which is either a string or a writer\nobject. It also takes an *fps* argument. This argument is different than the\n*interval* argument that `~.animation.FuncAnimation` or\n`~.animation.ArtistAnimation` uses. *fps* determines the frame rate that the\n**saved** animation uses, whereas *interval* determines the frame rate that\nthe **displayed** animation uses.\n\nBelow are a few examples that show how to save an animation with different\nwriters.\n\n\nPillow writers::\n\n  ani.save(filename=\"/tmp/pillow_example.gif\", writer=\"pillow\")\n  ani.save(filename=\"/tmp/pillow_example.apng\", writer=\"pillow\")\n\nHTML writers::\n\n  ani.save(filename=\"/tmp/html_example.html\", writer=\"html\")\n  ani.save(filename=\"/tmp/html_example.htm\", writer=\"html\")\n  ani.save(filename=\"/tmp/html_example.png\", writer=\"html\")\n\nFFMpegWriter::\n\n  ani.save(filename=\"/tmp/ffmpeg_example.mkv\", writer=\"ffmpeg\")\n  ani.save(filename=\"/tmp/ffmpeg_example.mp4\", writer=\"ffmpeg\")\n  ani.save(filename=\"/tmp/ffmpeg_example.mjpeg\", writer=\"ffmpeg\")\n\nImagemagick writers::\n\n  ani.save(filename=\"/tmp/imagemagick_example.gif\", writer=\"imagemagick\")\n  ani.save(filename=\"/tmp/imagemagick_example.webp\", writer=\"imagemagick\")\n  ani.save(filename=\"apng:/tmp/imagemagick_example.apng\",\n           writer=\"imagemagick\", extra_args=[\"-quality\", \"100\"])\n\n(the ``extra_args`` for *apng* are needed to reduce filesize by ~10x)\n\nNote that *ffmpeg* and *imagemagick* need to be separately installed.\nA cross-platform way to obtain *ffmpeg* is to install the ``imageio_ffmpeg``\nPyPI package, and then to set\n``rcParams[\"animation.ffmpeg_path\"] = imageio_ffmpeg.get_ffmpeg_exe()``.\n\n"
      ]
    }
  ],
  "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.14.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}