Home » Tutorial on the Matplotlib RangeSlider in Python

Tutorial on the Matplotlib RangeSlider in Python

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

The RangeSlider widget in Matplotlib allows you to create an interactive range slider with two handles, letting users select a range of values.

This widget is ideal for adjusting ranges interactively, especially for filtering data, setting plot limits, or zooming into specific parts of data.

In this tutorial, we’ll cover how to create and use the RangeSlider widget in Matplotlib, with examples demonstrating different applications, including filtering data, adjusting plot limits, and exploring data interactively.

1. Basic Setup for the RangeSlider

The RangeSlider widget allows you to interactively set a minimum and maximum value within a specified range. To set up a basic RangeSlider, you need to define it using RangeSlider from matplotlib.widgets.

Basic Structure of RangeSlider

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

# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)

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

# Adjust layout to make room for the RangeSlider
plt.subplots_adjust(bottom=0.25)

# Create an axis for the RangeSlider
ax_slider = plt.axes([0.25, 0.1, 0.5, 0.03])  # [left, bottom, width, height]

# Create the RangeSlider object
range_slider = RangeSlider(ax_slider, "Range", valmin=0, valmax=10, valinit=(2, 8))

# Update function to change the plot range based on RangeSlider values
def update(val):
    min_val, max_val = range_slider.val
    ax.set_xlim(min_val, max_val)
    fig.canvas.draw_idle()  # Redraw the plot

# Link the update function to RangeSlider value changes
range_slider.on_changed(update)
plt.show()

In this example:

  • RangeSlider(ax_slider, “Range”, valmin=0, valmax=10, valinit=(2, 8)) creates a slider labeled “Range” with minimum and maximum values from 0 to 10, and an initial range set from 2 to 8.
  • The update function dynamically adjusts the x-axis limits based on the slider’s selected range.

2. Filtering Data within a Selected Range

You can use the RangeSlider to filter data within a specific range. This example shows how to use it to display only the data points that fall within the selected range.

# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create figure and initial plot with full data
fig, ax = plt.subplots()
sc = ax.scatter(x, y)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.subplots_adjust(bottom=0.25)

# RangeSlider setup
ax_slider = plt.axes([0.25, 0.1, 0.5, 0.03])
range_slider = RangeSlider(ax_slider, "Filter Range", valmin=0, valmax=10, valinit=(2, 8))

# Update function to filter data based on RangeSlider values
def update(val):
    min_val, max_val = range_slider.val
    mask = (x >= min_val) & (x <= max_val)  # Filter condition
    sc.set_offsets(np.c_[x[mask], y[mask]])  # Update scatter plot
    fig.canvas.draw_idle()

# Link update function to RangeSlider
range_slider.on_changed(update)
plt.show()

In this example:

  • The update function filters the x and y data points within the selected range and updates the scatter plot to display only the filtered data points.

3. Using RangeSlider to Adjust Y-axis Limits in Real-Time

The RangeSlider can also be used to dynamically adjust the y-axis limits. This is useful for zooming in on specific value ranges or for adjusting visibility in data with large variations.

# Create figure and plot
fig, ax = plt.subplots()
line, = ax.plot(x, y, label="sin(x)")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.subplots_adjust(left=0.1, bottom=0.3)

# Set initial y-axis range to full data range
ax.set_ylim(-1, 1)

# RangeSlider for y-axis adjustment
ax_slider = plt.axes([0.2, 0.1, 0.65, 0.03])
range_slider = RangeSlider(ax_slider, "Y-axis Range", valmin=-1, valmax=1, valinit=(-0.5, 0.5))

# Update function to adjust y-axis limits based on RangeSlider
def update(val):
    y_min, y_max = range_slider.val
    ax.set_ylim(y_min, y_max)
    fig.canvas.draw_idle()

range_slider.on_changed(update)
plt.show()

In this example:

  • range_slider is used to set the y-axis limits between -1 and 1, allowing interactive adjustment of the visible y-range.

4. RangeSlider with Multiple Axes

If your plot contains multiple axes (e.g., subplots), you can use the RangeSlider to control specific properties across all axes. Here’s an example where the x-axis range is controlled across two subplots.

# Sample data
y_cos = np.cos(x)

# Create figure with two subplots
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
line1, = ax1.plot(x, y, label="sin(x)")
line2, = ax2.plot(x, y_cos, label="cos(x)")
ax1.legend()
ax2.legend()
plt.subplots_adjust(bottom=0.25)

# RangeSlider setup for shared x-axis adjustment
ax_slider = plt.axes([0.25, 0.1, 0.5, 0.03])
range_slider = RangeSlider(ax_slider, "X-axis Range", valmin=0, valmax=10, valinit=(2, 8))

# Update function to adjust x-axis limits across both subplots
def update(val):
    min_val, max_val = range_slider.val
    ax1.set_xlim(min_val, max_val)
    ax2.set_xlim(min_val, max_val)
    fig.canvas.draw_idle()

# Connect RangeSlider to the update function
range_slider.on_changed(update)
plt.show()

In this example:

  • The RangeSlider adjusts the x-axis limits across both subplots, keeping the plots in sync within the selected range.

5. Interactive Histogram Range Selection with RangeSlider

The RangeSlider is very effective for histograms, allowing you to filter bins within a specific range dynamically.

# Sample data
data = np.random.randn(1000)

# Create histogram
fig, ax = plt.subplots()
n, bins, patches = ax.hist(data, bins=30, color='skyblue', edgecolor='black')
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.subplots_adjust(bottom=0.25)

# RangeSlider setup for histogram range adjustment
ax_slider = plt.axes([0.25, 0.1, 0.5, 0.03])
range_slider = RangeSlider(ax_slider, "Histogram Range", valmin=bins[0], valmax=bins[-1], valinit=(bins[5], bins[25]))

# Update function to filter histogram within selected range
def update(val):
    min_val, max_val = range_slider.val
    # Update histogram by filtering the data within the range
    ax.cla()
    ax.hist(data[(data >= min_val) & (data <= max_val)], bins=30, color='skyblue', edgecolor='black')
    plt.xlabel("Value")
    plt.ylabel("Frequency")
    fig.canvas.draw_idle()

range_slider.on_changed(update)
plt.show()

In this example:

  • The histogram dynamically adjusts to only display values within the selected range, updating as the RangeSlider is adjusted.

6. Multiple RangeSliders for Different Parameters

You can use multiple RangeSliders to control different parameters. In this example, we use two RangeSliders to adjust both x-axis and y-axis limits.

# Create figure with sine wave plot
fig, ax = plt.subplots()
line, = ax.plot(x, y, label="sin(x)")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.subplots_adjust(left=0.1, bottom=0.3)

# X-axis RangeSlider
ax_x_slider = plt.axes([0.2, 0.15, 0.65, 0.03])
x_slider = RangeSlider(ax_x_slider, "X-axis Range", valmin=0, valmax=10, valinit=(2, 8))

# Y-axis RangeSlider
ax_y_slider = plt.axes([0.2, 0.05, 0.65, 0.03])
y_slider = RangeSlider(ax_y_slider, "Y-axis Range", valmin=-1, valmax=1, valinit=(-0.5, 0.5))

# Update function to adjust both x-axis and y-axis limits
def update(val):
    x_min, x_max = x_slider.val
    y_min, y_max = y_slider.val
    ax.set_xlim(x_min, x_max)
    ax.set_ylim(y_min, y_max)
    fig.canvas.draw_idle()

x_slider.on_changed(update)
y_slider.on_changed(update)
plt

.show()

In this example:

  • x_slider and y_slider control the x-axis and y-axis limits, respectively, allowing you to adjust both dimensions interactively.

Summary

In this tutorial, we covered various ways to use the Matplotlib RangeSlider widget for interactive range selection:

  1. Basic RangeSlider to adjust plot ranges.
  2. Filtering data within a selected range for scatter plots.
  3. Adjusting y-axis limits with a RangeSlider.
  4. Using RangeSlider with multiple subplots to control shared properties.
  5. Histogram range selection to filter displayed bins dynamically.
  6. Multiple RangeSliders to control both x-axis and y-axis limits.

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