{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\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.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport numpy as np"
      ]
    },
    {
      "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` would usually follow the following\nstructure:\n\n- Plot the initial figure, including all the required artists. Save all the\n  artists in variables so that they can be updated later on during the\n  animation.\n- Create an animation function that updates the data in each artist to\n  generate the new frame at each function call.\n- Create a `.FuncAnimation` object with the `.Figure` and the animation\n  function, along with the keyword arguments that determine the animation\n  properties.\n- Use `.animation.Animation.save` or `.pyplot.show` to save or show the\n  animation.\n\nThe update function uses the ``set_*`` function for different artists to\nmodify the data. The following table shows a few plotting methods, the artist\ntypes they return and some methods that can be used to update them.\n\n========================================  =============================  ===========================\nPlotting method                           Artist                         Set method\n========================================  =============================  ===========================\n`.Axes.plot`                              `.lines.Line2D`                `~.lines.Line2D.set_data`\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========================================  =============================  ===========================\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\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.11.1"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}