{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Slider\n\nIn this example, sliders are used to control the frequency and amplitude of\na sine wave.\n\nSee :doc:`/gallery/widgets/slider_snap_demo` for an example of having\nthe ``Slider`` snap to discrete values.\n\nSee :doc:`/gallery/widgets/range_slider` for an example of using\na ``RangeSlider`` to define a range of values.\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, Slider\n\n\n# The parametrized function to be plotted\ndef f(t, amplitude, frequency):\n return amplitude * np.sin(2 * np.pi * frequency * t)\n\nt = np.linspace(0, 1, 1000)\n\n# Define initial parameters\ninit_amplitude = 5\ninit_frequency = 3\n\n# Create the figure and the line that we will manipulate\nfig, ax = plt.subplots()\nline, = ax.plot(t, f(t, init_amplitude, init_frequency), lw=2)\nax.set_xlabel('Time [s]')\n\n# adjust the main plot to make room for the sliders\nfig.subplots_adjust(left=0.25, bottom=0.25)\n\n# Make a horizontal slider to control the frequency.\naxfreq = fig.add_axes([0.25, 0.1, 0.65, 0.03])\nfreq_slider = Slider(\n ax=axfreq,\n label='Frequency [Hz]',\n valmin=0.1,\n valmax=30,\n valinit=init_frequency,\n)\n\n# Make a vertically oriented slider to control the amplitude\naxamp = fig.add_axes([0.1, 0.25, 0.0225, 0.63])\namp_slider = Slider(\n ax=axamp,\n label=\"Amplitude\",\n valmin=0,\n valmax=10,\n valinit=init_amplitude,\n orientation=\"vertical\"\n)\n\n\n# The function to be called anytime a slider's value changes\ndef update(val):\n line.set_ydata(f(t, amp_slider.val, freq_slider.val))\n fig.canvas.draw_idle()\n\n\n# register the update function with each slider\nfreq_slider.on_changed(update)\namp_slider.on_changed(update)\n\n# Create a `matplotlib.widgets.Button` to reset the sliders to initial values.\nresetax = fig.add_axes([0.8, 0.025, 0.1, 0.04])\nbutton = Button(resetax, 'Reset', hovercolor='0.975')\n\n\ndef reset(event):\n freq_slider.reset()\n amp_slider.reset()\nbutton.on_clicked(reset)\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 - `matplotlib.widgets.Slider`\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 }