{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Bonus Example: Animations in notebooks" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import matplotlib.animation\n", "from IPython.display import HTML\n", "import numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Data:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "FRAMES = 50\n", "\n", "x = np.linspace(0, 2*np.pi)\n", "\n", "def f(x, phi=0):\n", " return np.sin(x - phi)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Animated figure:\n", "\n", "- `FuncAnimation` generates a sequence of images from a figure. \n", " Before each image the figure is updated using a callback function.\n", "- The animation can be rendered to HTML and then embedded in IPython." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", "line, = ax.plot(x, f(x))\n", "text = ax.set_title('Frame 0')\n", "\n", "def animate(i):\n", " phi = 2 * np.pi * i / FRAMES\n", " line.set_data(x, f(x, phi))\n", " text.set_text(F'Frame {i}')\n", "\n", "ani = matplotlib.animation.FuncAnimation(fig, animate, frames=FRAMES)\n", "plt.close(fig)\n", "HTML(ani.to_jshtml(fps=20))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", " Task: Add a title to the above animation, that displays the current phase phi.\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.4" } }, "nbformat": 4, "nbformat_minor": 4 }