Matplotlib Snapping Sliders

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to use Matplotlib to create sliders with discrete values. You will learn how to constrain the values of a slider to a set of allowed values and snap the slider values to those allowed values.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/InteractiveFeaturesGroup(["`Interactive Features`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/InteractiveFeaturesGroup -.-> matplotlib/interactive_backends("`Interactive Backends`") matplotlib/InteractiveFeaturesGroup -.-> matplotlib/widgets_sliders("`Widgets and Sliders`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/event_handling("`Event Handling`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") subgraph Lab Skills python/comments -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} matplotlib/importing_matplotlib -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} matplotlib/figures_axes -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} matplotlib/line_plots -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} matplotlib/interactive_backends -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} matplotlib/widgets_sliders -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} matplotlib/event_handling -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} python/for_loops -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} python/lists -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} python/tuples -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} python/function_definition -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} python/importing_modules -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} python/using_packages -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} python/numerical_computing -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} python/data_visualization -.-> lab-48947{{"`Matplotlib Snapping Sliders`"}} end

Import Required Libraries

In this step, you will import the required libraries for this lab. You will be using Matplotlib to create the sliders and NumPy to generate the data to be plotted.

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.widgets import Button, Slider

Generate Data

In this step, you will generate the data to be plotted. You will create a sine wave with a frequency of 3 Hz and an amplitude of 5.

t = np.arange(0.0, 1.0, 0.001)
a0 = 5
f0 = 3
s = a0 * np.sin(2 * np.pi * f0 * t)

Create the Figure and Axes

In this step, you will create the figure and axes for the plot. You will also adjust the position of the axes to make room for the sliders.

fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.25)
l, = ax.plot(t, s, lw=2)

ax_freq = fig.add_axes([0.25, 0.1, 0.65, 0.03])
ax_amp = fig.add_axes([0.25, 0.15, 0.65, 0.03])

Define Allowed Values for the Amplitude Slider

In this step, you will define the allowed values for the amplitude slider. The amplitude slider will use these values to snap to the nearest allowed value.

## define the values to use for snapping
allowed_amplitudes = np.concatenate([np.linspace(.1, 5, 100), [6, 7, 8, 9]])

Create the Sliders

In this step, you will create the sliders. You will create one slider for the amplitude and one slider for the frequency.

samp = Slider(
    ax_amp, "Amp", 0.1, 9.0,
    valinit=a0, valstep=allowed_amplitudes,
    color="green"
)

sfreq = Slider(
    ax_freq, "Freq", 0, 10*np.pi,
    valinit=2*np.pi, valstep=np.pi,
    initcolor='none'  ## Remove the line marking the valinit position.
)

Create the Update Function

In this step, you will create the update function for the sliders. This function will update the plot when the slider values are changed.

def update(val):
    amp = samp.val
    freq = sfreq.val
    l.set_ydata(amp*np.sin(2*np.pi*freq*t))
    fig.canvas.draw_idle()

Connect the Sliders to the Update Function

In this step, you will connect the sliders to the update function. This will ensure that the plot is updated whenever the slider values are changed.

sfreq.on_changed(update)
samp.on_changed(update)

Create the Reset Button

In this step, you will create a reset button for the sliders. When clicked, the reset button will reset the slider values to their initial values.

ax_reset = fig.add_axes([0.8, 0.025, 0.1, 0.04])
button = Button(ax_reset, 'Reset', hovercolor='0.975')

def reset(event):
    sfreq.reset()
    samp.reset()
button.on_clicked(reset)

Show the Plot

In this step, you will show the plot.

plt.show()

Summary

In this lab, you learned how to use Matplotlib to create sliders with discrete values. You learned how to constrain the values of a slider to a set of allowed values and snap the slider values to those allowed values. You also learned how to create a reset button for the sliders.

Other Python Tutorials you may like