Home » Tutorial on the Matplotlib Radio Buttons Widget in Python

Tutorial on the Matplotlib Radio Buttons Widget in Python

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

The RadioButtons widget in Matplotlib is a tool for creating a list of options where only one can be selected at a time.

This widget is particularly useful for switching between different data views, adjusting plot properties, and creating interactive visualizations by allowing users to toggle between settings.

In this tutorial, we’ll cover how to create and use the RadioButtons widget in Matplotlib with examples, including toggling between different functions, switching between colors and styles, and managing multiple plot properties interactively.

1. Basic Setup for Radio Buttons

The RadioButtons widget in Matplotlib allows you to provide a list of options, only one of which can be active at a time. Each option triggers a callback function when selected.

Basic Structure of RadioButtons

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

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

# Create figure and initial plot
fig, ax = plt.subplots()
line, = ax.plot(x, y1, label="sin(x)")
ax.legend()
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

# Create the RadioButtons widget
rax = plt.axes([0.75, 0.4, 0.15, 0.15], frameon=True)  # Position for the radio buttons
radio = RadioButtons(rax, ('sin(x)', 'cos(x)'))

# Define callback function to update plot
def update_plot(label):
    if label == 'sin(x)':
        line.set_ydata(y1)
    elif label == 'cos(x)':
        line.set_ydata(y2)
    line.set_label(label)
    ax.legend()
    plt.draw()

# Link radio buttons to the callback function
radio.on_clicked(update_plot)
plt.show()

In this example:

  • RadioButtons(rax, (‘sin(x)', ‘cos(x)')) creates two radio button options, ‘sin(x)' and ‘cos(x)'.
  • The update_plot function updates the line plot based on the selected option.
  • The on_clicked method links each button to the update_plot function, triggering the update when an option is selected.

2. Customizing Radio Buttons Appearance

The appearance of radio buttons can be customized using parameters like activecolor for the selected button and adjusting the font properties.

# Customize radio button colors and fonts
fig, ax = plt.subplots()
line, = ax.plot(x, y1, label="sin(x)")
ax.legend()

# Create radio buttons with customized appearance
rax = plt.axes([0.75, 0.4, 0.15, 0.15], frameon=True)
radio = RadioButtons(rax, ('sin(x)', 'cos(x)'), activecolor='orange')

# Set font properties of labels
for label in radio.labels:
    label.set_fontsize(12)
    label.set_color('blue')

# Callback function
def update_plot(label):
    if label == 'sin(x)':
        line.set_ydata(y1)
    elif label == 'cos(x)':
        line.set_ydata(y2)
    line.set_label(label)
    ax.legend()
    plt.draw()

# Link radio buttons to the callback function
radio.on_clicked(update_plot)
plt.show()

In this example:

  • activecolor='orange' changes the color of the active radio button.
  • The font size and color of the button labels are customized by iterating over radio.labels.

3. Switching Between Multiple Data Sets with Radio Buttons

You can use radio buttons to toggle between multiple datasets on the same plot. This example adds a third option to display the tangent function.

# Additional data
y3 = np.tan(x)

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

# Create radio buttons
rax = plt.axes([0.75, 0.3, 0.15, 0.2], frameon=True)
radio = RadioButtons(rax, ('sin(x)', 'cos(x)', 'tan(x)'))

# Callback function to update plot
def update_plot(label):
    if label == 'sin(x)':
        line.set_ydata(y1)
    elif label == 'cos(x)':
        line.set_ydata(y2)
    elif label == 'tan(x)':
        line.set_ydata(np.where(np.abs(y3) < 10, y3, np.nan))  # Limit large values for tan
    line.set_label(label)
    ax.legend()
    plt.draw()

radio.on_clicked(update_plot)
plt.show()

In this example:

  • np.where(np.abs(y3) < 10, y3, np.nan) is used to handle extreme values in the tangent function, preventing large jumps in the plot.

4. Using Radio Buttons to Toggle Plot Properties

You can use radio buttons to change properties of the plot, such as color, line style, or width.

# Create plot with initial line style and color
fig, ax = plt.subplots()
line, = ax.plot(x, y1, label="sin(x)", color='blue', linestyle='-', linewidth=2)
ax.legend()

# Radio buttons for color, line style, and width
color_ax = plt.axes([0.75, 0.7, 0.15, 0.15], frameon=True)
color_radio = RadioButtons(color_ax, ('blue', 'green', 'red'), activecolor='blue')

style_ax = plt.axes([0.75, 0.5, 0.15, 0.15], frameon=True)
style_radio = RadioButtons(style_ax, ('-', '--', '-.'), activecolor='green')

width_ax = plt.axes([0.75, 0.3, 0.15, 0.15], frameon=True)
width_radio = RadioButtons(width_ax, ('1', '2', '3'), activecolor='purple')

# Callback functions to update line properties
def update_color(label):
    line.set_color(label)
    plt.draw()

def update_style(label):
    line.set_linestyle(label)
    plt.draw()

def update_width(label):
    line.set_linewidth(int(label))
    plt.draw()

# Connect radio buttons to callback functions
color_radio.on_clicked(update_color)
style_radio.on_clicked(update_style)
width_radio.on_clicked(update_width)
plt.show()

In this example:

  • color_radio, style_radio, and width_radio control the line color, style, and width, respectively.
  • Each radio button group has a separate callback function that updates the plot properties based on the selected option.

5. Using Radio Buttons with Subplots

Radio buttons can control multiple subplots, allowing you to switch views or data on different axes interactively.

# Create subplots with different data
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 8))
x = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)

# Plot initial data in both subplots
line1, = ax1.plot(x, y1, label="sin(x)")
line2, = ax2.plot(x, y2, label="cos(x)")
ax1.legend()
ax2.legend()

# Create radio buttons
rax = plt.axes([0.75, 0.3, 0.15, 0.3], frameon=True)
radio = RadioButtons(rax, ('sin(x)', 'cos(x)', 'tan(x)'))

# Callback function to update both subplots
def update_subplots(label):
    if label == 'sin(x)':
        line1.set_ydata(y1)
        line2.set_ydata(y1)
    elif label == 'cos(x)':
        line1.set_ydata(y2)
        line2.set_ydata(y2)
    elif label == 'tan(x)':
        line1.set_ydata(np.where(np.abs(y3) < 10, y3, np.nan))
        line2.set_ydata(np.where(np.abs(y3) < 10, y3, np.nan))
    
    line1.set_label(label)
    line2.set_label(label)
    ax1.legend()
    ax2.legend()
    plt.draw()

radio.on_clicked(update_subplots)
plt.show()

In this example:

  • Both subplots are updated based on the selected radio button option.

6. Using Radio Buttons to Toggle Visibility of Multiple Lines

Radio buttons can also be used to selectively show or hide lines in a plot, effectively turning on and off specific data series.

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

# Create 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 radio buttons to toggle line visibility
rax = plt.axes([0.75, 0.3, 0.15, 0.3], frameon=True)
radio = RadioButtons(rax, ('sin(x)', '

cos(x)', 'tan(x)'))

# Callback function to toggle line visibility
def toggle_visibility(label):
    line1.set_visible(label == 'sin(x)')
    line2.set_visible(label == 'cos(x)')
    line3.set_visible(label == 'tan(x)')
    ax.legend()
    plt.draw()

radio.on_clicked(toggle_visibility)
plt.show()

In this example:

  • Each radio button toggles the visibility of one line, hiding the others, allowing the user to focus on specific data series.

Summary

This tutorial covered various applications of the RadioButtons widget in Matplotlib to create interactive plots:

  1. Basic Setup for Radio Buttons to switch between datasets.
  2. Customizing Appearance of radio buttons.
  3. Switching Between Multiple Datasets with additional options.
  4. Toggling Plot Properties like color, style, and width.
  5. Using Radio Buttons with Multiple Subplots to update multiple views.
  6. Controlling Visibility of Multiple Lines to selectively display data.

The RadioButtons widget adds interactivity to Matplotlib plots, allowing users to control plot properties or data visibility interactively.

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