Home » Tutorial on the Matplotlib Check Buttons Widget in Python

Tutorial on the Matplotlib Check Buttons Widget in Python

Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Programmer I [1Z0-815] Practice Tests
Spring Framework Basics Video Course
Oracle Java Certification
Java SE 11 Developer (Upgrade) [1Z0-817]
1 Year Subscription

The CheckButtons widget in Matplotlib allows you to create checkboxes that can be toggled independently.

Unlike radio buttons, multiple check buttons can be selected at once, making this widget useful for showing and hiding multiple datasets, toggling various plot features, or controlling multiple elements simultaneously in an interactive plot.

In this tutorial, we’ll cover how to create and use the CheckButtons widget in Matplotlib, with examples showing how to toggle visibility of multiple lines, control plot properties, and manage multiple subplots interactively.

1. Basic Setup for Check Buttons

The CheckButtons widget allows you to create a list of options, each with a checkbox that can be checked or unchecked independently. Each option triggers a callback function whenever it’s toggled.

Basic Structure of CheckButtons

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

# Sample data for multiple lines
x = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)

# Create a figure and initial plot with multiple lines
fig, ax = plt.subplots()
line1, = ax.plot(x, y1, label="sin(x)")
line2, = ax.plot(x, y2, label="cos(x)")
line3, = ax.plot(x, np.where(np.abs(y3) < 10, y3, np.nan), label="tan(x)")
ax.legend()

# Create the CheckButtons widget
rax = plt.axes([0.75, 0.4, 0.15, 0.2], frameon=True)  # Position of the check buttons
check = CheckButtons(rax, ['sin(x)', 'cos(x)', 'tan(x)'], [True, True, True])

# Define callback function to toggle visibility
def toggle_visibility(label):
    if label == 'sin(x)':
        line1.set_visible(not line1.get_visible())
    elif label == 'cos(x)':
        line2.set_visible(not line2.get_visible())
    elif label == 'tan(x)':
        line3.set_visible(not line3.get_visible())
    plt.draw()

# Link check buttons to the callback function
check.on_clicked(toggle_visibility)
plt.show()

In this example:

  • CheckButtons(rax, [‘sin(x)', ‘cos(x)', ‘tan(x)'], [True, True, True]) creates check buttons for three options, all initially checked.
  • The toggle_visibility function toggles the visibility of each line based on the selected option.
  • check.on_clicked(toggle_visibility) links each button to the toggle_visibility function, which is triggered whenever a checkbox is toggled.

2. Customizing Check Buttons Appearance

The appearance of check buttons can be customized by adjusting the properties of the check box labels and setting the background color.

# Create figure and initial plot with multiple lines
fig, ax = plt.subplots()
line1, = ax.plot(x, y1, label="sin(x)")
line2, = ax.plot(x, y2, label="cos(x)")
line3, = ax.plot(x, np.where(np.abs(y3) < 10, y3, np.nan), label="tan(x)")
ax.legend()

# Customize check button appearance
rax = plt.axes([0.75, 0.4, 0.15, 0.2], frameon=True)
check = CheckButtons(rax, ['sin(x)', 'cos(x)', 'tan(x)'], [True, True, True])

# Set background color of buttons
rax.set_facecolor('lightgray')

# Customize font properties
for label in check.labels:
    label.set_fontsize(12)
    label.set_color('darkblue')

# Callback function to toggle visibility
def toggle_visibility(label):
    if label == 'sin(x)':
        line1.set_visible(not line1.get_visible())
    elif label == 'cos(x)':
        line2.set_visible(not line2.get_visible())
    elif label == 'tan(x)':
        line3.set_visible(not line3.get_visible())
    plt.draw()

check.on_clicked(toggle_visibility)
plt.show()

In this example:

  • rax.set_facecolor(‘lightgray') sets the background color of the check button box.
  • label.set_fontsize(12) and label.set_color(‘darkblue') adjust the font size and color for each label.

3. Using Check Buttons to Toggle Multiple Plot Properties

Check buttons can be used to control various plot properties like grid, axis visibility, or legend display.

# Create figure and plot
fig, ax = plt.subplots()
ax.plot(x, y1, label="sin(x)")
ax.legend()

# Create CheckButtons for plot properties
rax = plt.axes([0.75, 0.4, 0.15, 0.2], frameon=True)
check = CheckButtons(rax, ['Show Grid', 'Show Legend', 'Show Axis'], [False, True, True])

# Callback function to toggle properties
def toggle_properties(label):
    if label == 'Show Grid':
        ax.grid(visible=not ax.xaxis._gridOnMajor)
    elif label == 'Show Legend':
        ax.legend().set_visible(not ax.get_legend().get_visible())
    elif label == 'Show Axis':
        ax.axis('on' if ax.axison else 'off')
    plt.draw()

# Link check buttons to the callback function
check.on_clicked(toggle_properties)
plt.show()

In this example:

  • toggle_properties manages the visibility of grid, legend, and axis based on the selected checkboxes.

4. Using Check Buttons with Subplots

Check buttons can control the visibility of multiple plots within a figure that contains subplots.

# Sample data for subplots
y_cos = np.cos(x)
y_tan = np.tan(x)

# Create figure with two subplots
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 8))
line1, = ax1.plot(x, y1, label="sin(x)")
line2, = ax2.plot(x, y_cos, label="cos(x)")
line3, = ax2.plot(x, np.where(np.abs(y_tan) < 10, y_tan, np.nan), label="tan(x)")
ax1.legend()
ax2.legend()

# Create CheckButtons for subplot visibility
rax = plt.axes([0.75, 0.4, 0.15, 0.2], frameon=True)
check = CheckButtons(rax, ['sin(x)', 'cos(x)', 'tan(x)'], [True, True, True])

# Callback function to toggle visibility in subplots
def toggle_subplot_visibility(label):
    if label == 'sin(x)':
        line1.set_visible(not line1.get_visible())
    elif label == 'cos(x)':
        line2.set_visible(not line2.get_visible())
    elif label == 'tan(x)':
        line3.set_visible(not line3.get_visible())
    plt.draw()

check.on_clicked(toggle_subplot_visibility)
plt.show()

In this example:

  • The toggle_subplot_visibility function toggles visibility of lines across multiple subplots.

5. Using Check Buttons to Control Line Styles

Check buttons can also be used to toggle line styles dynamically. In this example, check buttons allow toggling between solid, dashed, and dotted line styles.

# Create plot
fig, ax = plt.subplots()
line, = ax.plot(x, y1, label="sin(x)", linestyle='-')
plt.legend()

# Create CheckButtons for line style
rax = plt.axes([0.75, 0.4, 0.15, 0.15], frameon=True)
check = CheckButtons(rax, ['Solid', 'Dashed', 'Dotted'], [True, False, False])

# Callback function to toggle line style
def toggle_line_style(label):
    if label == 'Solid':
        line.set_linestyle('-')
    elif label == 'Dashed':
        line.set_linestyle('--')
    elif label == 'Dotted':
        line.set_linestyle(':')
    
    # Uncheck other buttons to reflect exclusive selection
    for other_label in check.labels:
        if other_label.get_text() != label:
            check.set_active(check.labels.index(other_label)) if other_label.get_text() == label else other_label.set_color('lightgray')

    plt.draw()

check.on_clicked(toggle_line_style)
plt.show()

In this example:

  • The toggle_line_style function switches the line style based on which checkbox is selected, and sets other check buttons to an “inactive” look to mimic a radio button behavior, where only one option should be selected.

6. Changing Plot Features with Multiple Check Buttons

You can use multiple check buttons to toggle various plot features such as showing data markers or adjusting line width. Here’s an example that combines several different features.

# Create figure and plot
fig, ax = plt.subplots()
line, = ax.plot(x, y1, label="sin(x)", linewidth=1, marker='o', markersize=0)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

# Create CheckButtons for plot features
rax = plt.axes([0.75, 0.4, 0.15, 0.2], frameon=True)
check = CheckButtons(rax, ['Show Markers', 'Thicker Line'], [False, False])

# Callback function to toggle features
def toggle_features(label):
    if label == 'Show Markers':
        if line.get_markersize()

 == 0:
            line.set_markersize(5)
        else:
            line.set_markersize(0)
    elif label == 'Thicker Line':
        line.set_linewidth(3 if line.get_linewidth() == 1 else 1)
    plt.draw()

check.on_clicked(toggle_features)
plt.show()

In this example:

  • Show Markers controls the marker visibility by toggling the marker size.
  • Thicker Line adjusts the line width between 1 and 3.

Summary

In this tutorial, we covered several ways to use the CheckButtons widget in Matplotlib to add interactivity to your plots:

  1. Basic Setup for Check Buttons to toggle visibility of multiple lines.
  2. Customizing Appearance of the check buttons.
  3. Using Check Buttons to Toggle Plot Properties like grid, legend, and axis.
  4. Working with Subplots to control multiple plots interactively.
  5. Controlling Line Styles to switch between solid, dashed, and dotted lines.
  6. Toggling Multiple Plot Features such as markers and line width.

The CheckButtons widget is a versatile tool in Matplotlib that allows you to create interactive visualizations where users can control various aspects of the plot with ease.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More