Matplotlib Radio Button Sine Wave Visualization

PythonPythonBeginner
Practice Now

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

Introduction

Radio buttons are a type of input element that allows users to select one option from a group of predefined options. In this lab, we will use the matplotlib library to create a visualization with radio buttons that let the user choose between different sine waves to be shown in the plot.

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/PlotCustomizationGroup(["`Plot Customization`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/InteractiveFeaturesGroup(["`Interactive Features`"]) 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/PlotCustomizationGroup -.-> matplotlib/line_styles_colors("`Customizing Line Styles and Colors`") matplotlib/InteractiveFeaturesGroup -.-> matplotlib/interactive_backends("`Interactive Backends`") matplotlib/InteractiveFeaturesGroup -.-> matplotlib/widgets_sliders("`Widgets and Sliders`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") 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-48898{{"`Matplotlib Radio Button Sine Wave Visualization`"}} matplotlib/figures_axes -.-> lab-48898{{"`Matplotlib Radio Button Sine Wave Visualization`"}} matplotlib/line_plots -.-> lab-48898{{"`Matplotlib Radio Button Sine Wave Visualization`"}} matplotlib/line_styles_colors -.-> lab-48898{{"`Matplotlib Radio Button Sine Wave Visualization`"}} matplotlib/interactive_backends -.-> lab-48898{{"`Matplotlib Radio Button Sine Wave Visualization`"}} matplotlib/widgets_sliders -.-> lab-48898{{"`Matplotlib Radio Button Sine Wave Visualization`"}} python/lists -.-> lab-48898{{"`Matplotlib Radio Button Sine Wave Visualization`"}} python/tuples -.-> lab-48898{{"`Matplotlib Radio Button Sine Wave Visualization`"}} python/dictionaries -.-> lab-48898{{"`Matplotlib Radio Button Sine Wave Visualization`"}} python/function_definition -.-> lab-48898{{"`Matplotlib Radio Button Sine Wave Visualization`"}} python/importing_modules -.-> lab-48898{{"`Matplotlib Radio Button Sine Wave Visualization`"}} python/using_packages -.-> lab-48898{{"`Matplotlib Radio Button Sine Wave Visualization`"}} python/numerical_computing -.-> lab-48898{{"`Matplotlib Radio Button Sine Wave Visualization`"}} python/data_visualization -.-> lab-48898{{"`Matplotlib Radio Button Sine Wave Visualization`"}} end

Import Required Libraries

We will start by importing the required libraries for this lab - numpy and matplotlib.

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.widgets import RadioButtons

Create Data

Next, we will create the data that will be used in the plot. We will create three different sine waves with different frequencies using the numpy library.

t = np.arange(0.0, 2.0, 0.01)
s0 = np.sin(2*np.pi*t)
s1 = np.sin(4*np.pi*t)
s2 = np.sin(8*np.pi*t)

Create the Plot and Radio Buttons

Now, we will create the plot and radio buttons. We will use the subplots() function to create the plot and the RadioButtons() function to create the radio buttons.

fig, ax = plt.subplots()
l, = ax.plot(t, s0, lw=2, color='red')
fig.subplots_adjust(left=0.3)

axcolor = 'lightgoldenrodyellow'
rax = fig.add_axes([0.05, 0.7, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, ('1 Hz', '2 Hz', '4 Hz'),
                     label_props={'color': 'cmy', 'fontsize': [12, 14, 16]},
                     radio_props={'s': [16, 32, 64]})

Add Functionality to the Radio Buttons

We will now add functionality to the radio buttons using the on_clicked() function. We will define two functions - hzfunc() and colorfunc() - that will be called when the radio buttons are clicked.

def hzfunc(label):
    hzdict = {'1 Hz': s0, '2 Hz': s1, '4 Hz': s2}
    ydata = hzdict[label]
    l.set_ydata(ydata)
    fig.canvas.draw()
radio.on_clicked(hzfunc)

rax = fig.add_axes([0.05, 0.4, 0.15, 0.15], facecolor=axcolor)
radio2 = RadioButtons(
    rax, ('red', 'blue', 'green'),
    label_props={'color': ['red', 'blue', 'green']},
    radio_props={
        'facecolor': ['red', 'blue', 'green'],
        'edgecolor': ['darkred', 'darkblue', 'darkgreen'],
    })


def colorfunc(label):
    l.set_color(label)
    fig.canvas.draw()
radio2.on_clicked(colorfunc)

rax = fig.add_axes([0.05, 0.1, 0.15, 0.15], facecolor=axcolor)
radio3 = RadioButtons(rax, ('-', '--', '-.', ':'))


def stylefunc(label):
    l.set_linestyle(label)
    fig.canvas.draw()
radio3.on_clicked(stylefunc)

Display the Plot

Finally, we will display the plot using the show() function.

plt.show()

Summary

In this lab, we learned how to create a visualization with radio buttons using the matplotlib library. We used radio buttons to let the user choose between different sine waves to be shown in the plot. We also added functionality to the radio buttons by defining functions that were called when the buttons were clicked. Overall, this lab demonstrated how radio buttons can be used to create interactive visualizations that allow users to explore different aspects of the data.

Other Python Tutorials you may like