Create Sine Wave Sliders with Matplotlib

MatplotlibMatplotlibBeginner
Practice Now

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

Introduction

In this tutorial, we will learn how to create sliders and use them to control a sine wave's frequency and amplitude. We will use the Matplotlib library to create a graph of the sine wave and the sliders. The sliders will allow us to adjust the frequency and amplitude of the sine wave.

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 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/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) 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/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 matplotlib/importing_matplotlib -.-> lab-48946{{"`Create Sine Wave Sliders with Matplotlib`"}} matplotlib/figures_axes -.-> lab-48946{{"`Create Sine Wave Sliders with Matplotlib`"}} matplotlib/line_plots -.-> lab-48946{{"`Create Sine Wave Sliders with Matplotlib`"}} matplotlib/interactive_backends -.-> lab-48946{{"`Create Sine Wave Sliders with Matplotlib`"}} matplotlib/widgets_sliders -.-> lab-48946{{"`Create Sine Wave Sliders with Matplotlib`"}} matplotlib/event_handling -.-> lab-48946{{"`Create Sine Wave Sliders with Matplotlib`"}} python/lists -.-> lab-48946{{"`Create Sine Wave Sliders with Matplotlib`"}} python/tuples -.-> lab-48946{{"`Create Sine Wave Sliders with Matplotlib`"}} python/function_definition -.-> lab-48946{{"`Create Sine Wave Sliders with Matplotlib`"}} python/importing_modules -.-> lab-48946{{"`Create Sine Wave Sliders with Matplotlib`"}} python/using_packages -.-> lab-48946{{"`Create Sine Wave Sliders with Matplotlib`"}} python/numerical_computing -.-> lab-48946{{"`Create Sine Wave Sliders with Matplotlib`"}} python/data_visualization -.-> lab-48946{{"`Create Sine Wave Sliders with Matplotlib`"}} end

Import Libraries

The first step is to import the necessary libraries. We will be using Matplotlib and NumPy.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Button, Slider

Define the Sine Wave Function

Next, we will define the function that will generate our sine wave. The function will take in two parameters, amplitude and frequency, and return the sine wave at a given time.

def f(t, amplitude, frequency):
    return amplitude * np.sin(2 * np.pi * frequency * t)

Create the Initial Graph

Now, we will create the initial graph of the sine wave. We will define the initial parameters for the amplitude and frequency and plot the sine wave using those parameters.

t = np.linspace(0, 1, 1000)
init_amplitude = 5
init_frequency = 3

fig, ax = plt.subplots()
line, = ax.plot(t, f(t, init_amplitude, init_frequency), lw=2)
ax.set_xlabel('Time [s]')

Create the Sliders

We will now create the sliders that will allow us to adjust the frequency and amplitude of the sine wave. We will create a horizontal slider to control the frequency and a vertical slider to control the amplitude.

fig.subplots_adjust(left=0.25, bottom=0.25)
axfreq = fig.add_axes([0.25, 0.1, 0.65, 0.03])
freq_slider = Slider(
    ax=axfreq,
    label='Frequency [Hz]',
    valmin=0.1,
    valmax=30,
    valinit=init_frequency,
)

axamp = fig.add_axes([0.1, 0.25, 0.0225, 0.63])
amp_slider = Slider(
    ax=axamp,
    label="Amplitude",
    valmin=0,
    valmax=10,
    valinit=init_amplitude,
    orientation="vertical"
)

Create the Update Function

We will now create the function that will update the sine wave every time we adjust the sliders. The function will take in the values of the amplitude and frequency sliders, and update the sine wave accordingly.

def update(val):
    line.set_ydata(f(t, amp_slider.val, freq_slider.val))
    fig.canvas.draw_idle()

Register the Update Function with the Sliders

Next, we will register the update function with each slider so that the function is called every time we adjust the sliders.

freq_slider.on_changed(update)
amp_slider.on_changed(update)

Create the Reset Button

We will now create a reset button that will reset the sliders to their initial values.

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

def reset(event):
    freq_slider.reset()
    amp_slider.reset()
button.on_clicked(reset)

Show the Graph

Finally, we will show the graph with the sliders and the reset button.

plt.show()

Summary

In this tutorial, we learned how to create sliders and use them to control a sine wave's frequency and amplitude. We used the Matplotlib library to create a graph of the sine wave and the sliders. We created a horizontal slider to control the frequency and a vertical slider to control the amplitude. We also created a reset button that reset the sliders to their initial values.

Other Matplotlib Tutorials you may like