{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Buttons\n\nConstructing a simple button GUI to modify a sine wave.\n\nThe ``next`` and ``previous`` button widget helps visualize the wave with\nnew frequencies.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.widgets import Button\n\nfreqs = np.arange(2, 20, 3)\n\nfig, ax = plt.subplots()\nfig.subplots_adjust(bottom=0.2)\nt = np.arange(0.0, 1.0, 0.001)\ns = np.sin(2*np.pi*freqs[0]*t)\nl, = ax.plot(t, s, lw=2)\n\n\nclass Index:\n ind = 0\n\n def next(self, event):\n self.ind += 1\n i = self.ind % len(freqs)\n ydata = np.sin(2*np.pi*freqs[i]*t)\n l.set_ydata(ydata)\n plt.draw()\n\n def prev(self, event):\n self.ind -= 1\n i = self.ind % len(freqs)\n ydata = np.sin(2*np.pi*freqs[i]*t)\n l.set_ydata(ydata)\n plt.draw()\n\ncallback = Index()\naxprev = fig.add_axes([0.7, 0.05, 0.1, 0.075])\naxnext = fig.add_axes([0.81, 0.05, 0.1, 0.075])\nbnext = Button(axnext, 'Next')\nbnext.on_clicked(callback.next)\nbprev = Button(axprev, 'Previous')\nbprev.on_clicked(callback.prev)\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. admonition:: References\n\n The use of the following functions, methods, classes and modules is shown\n in this example:\n\n - `matplotlib.widgets.Button`\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.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }