{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Decay\n\nThis example showcases:\n\n- using a generator to drive an animation,\n- changing axes limits during an animation.\n\nOutput generated via `matplotlib.animation.Animation.to_jshtml`.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import itertools\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport matplotlib.animation as animation\n\n\ndef data_gen():\n for cnt in itertools.count():\n t = cnt / 10\n yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)\n\n\ndef init():\n ax.set_ylim(-1.1, 1.1)\n ax.set_xlim(0, 1)\n del xdata[:]\n del ydata[:]\n line.set_data(xdata, ydata)\n return line,\n\nfig, ax = plt.subplots()\nline, = ax.plot([], [], lw=2)\nax.grid()\nxdata, ydata = [], []\n\n\ndef run(data):\n # update the data\n t, y = data\n xdata.append(t)\n ydata.append(y)\n xmin, xmax = ax.get_xlim()\n\n if t >= xmax:\n ax.set_xlim(xmin, 2*xmax)\n ax.figure.canvas.draw()\n line.set_data(xdata, ydata)\n\n return line,\n\n# Only save last 100 frames, but run forever\nani = animation.FuncAnimation(fig, run, data_gen, interval=100, init_func=init,\n save_count=100)\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 }