{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Pause and resume an animation\n\nThis example showcases:\n\n- using the Animation.pause() method to pause an animation.\n- using the Animation.resume() method to resume an animation.\n\n

Note

This example exercises the interactive capabilities of Matplotlib, and this\n will not appear in the static documentation. Please run this code on your\n machine to see the interactivity.\n\n You can copy and paste individual parts, or download the entire example\n using the link at the bottom of the page.

\n\nOutput generated via `matplotlib.animation.Animation.to_jshtml`.\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\n\n\nclass PauseAnimation:\n def __init__(self):\n fig, ax = plt.subplots()\n ax.set_title('Click to pause/resume the animation')\n x = np.linspace(-0.1, 0.1, 1000)\n\n # Start with a normal distribution\n self.n0 = (1.0 / ((4 * np.pi * 2e-4 * 0.1) ** 0.5)\n * np.exp(-x ** 2 / (4 * 2e-4 * 0.1)))\n self.p, = ax.plot(x, self.n0)\n\n self.animation = animation.FuncAnimation(\n fig, self.update, frames=200, interval=50, blit=True)\n self.paused = False\n\n fig.canvas.mpl_connect('button_press_event', self.toggle_pause)\n\n def toggle_pause(self, *args, **kwargs):\n if self.paused:\n self.animation.resume()\n else:\n self.animation.pause()\n self.paused = not self.paused\n\n def update(self, i):\n self.n0 += i / 100 % 5\n self.p.set_ydata(self.n0 % 20)\n return (self.p,)\n\n\npa = PauseAnimation()\nplt.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.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }