Using Check Buttons in Matplotlib

PythonPythonBeginner
Practice Now

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

Introduction

This lab will demonstrate how to use check buttons in Python Matplotlib. Check buttons allow users to turn visual elements on and off with check buttons, similar to check boxes. We will use the CheckButtons function to create a plot with three different sine waves, and the ability to choose which waves are displayed with the check buttons.

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`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) 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`"]) 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`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") 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-48601{{"`Using Check Buttons in Matplotlib`"}} matplotlib/figures_axes -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} matplotlib/line_plots -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} matplotlib/interactive_backends -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} matplotlib/widgets_sliders -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} python/booleans -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} python/for_loops -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} python/list_comprehensions -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} python/lists -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} python/tuples -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} python/dictionaries -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} python/function_definition -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} python/importing_modules -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} python/using_packages -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} python/numerical_computing -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} python/data_visualization -.-> lab-48601{{"`Using Check Buttons in Matplotlib`"}} end

Import Libraries

We will start by importing the necessary libraries. We need numpy for generating the data and matplotlib for creating the plot.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import CheckButtons

Generate Data

Next, we will generate the data for our plot. We will create three sine waves with different frequencies using numpy.

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(6*np.pi*t)

Create the Plot

Now, we will create the plot using matplotlib. We will plot the three sine waves on the same graph and set the visibility of the first wave to False since we want to start with it hidden.

fig, ax = plt.subplots()
l0, = ax.plot(t, s0, visible=False, lw=2, color='black', label='1 Hz')
l1, = ax.plot(t, s1, lw=2, color='red', label='2 Hz')
l2, = ax.plot(t, s2, lw=2, color='green', label='3 Hz')
fig.subplots_adjust(left=0.2)

Add Check Buttons

We will now add the check buttons to our plot using the CheckButtons function. We will pass the plotted lines as labels and set the initial visibility of each line. We will also adjust the properties of the check buttons to match the colors of the plotted lines.

lines_by_label = {l.get_label(): l for l in [l0, l1, l2]}
line_colors = [l.get_color() for l in lines_by_label.values()]

rax = fig.add_axes([0.05, 0.4, 0.1, 0.15])
check = CheckButtons(
    ax=rax,
    labels=lines_by_label.keys(),
    actives=[l.get_visible() for l in lines_by_label.values()],
    label_props={'color': line_colors},
    frame_props={'edgecolor': line_colors},
    check_props={'facecolor': line_colors},
)

Define Callback Function

We need to define a callback function for the check buttons. This function will be called every time a check button is clicked. We will use this function to toggle the visibility of the corresponding line on the plot.

def callback(label):
    ln = lines_by_label[label]
    ln.set_visible(not ln.get_visible())
    ln.figure.canvas.draw_idle()

check.on_clicked(callback)

Display the Plot

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

plt.show()

Summary

In this lab, we learned how to use check buttons in Python Matplotlib. We created a plot with three different sine waves, and the ability to choose which waves are displayed with the check buttons. We used the CheckButtons function to create the buttons and defined a callback function to toggle the visibility of the corresponding line on the plot.

Other Python Tutorials you may like