Matplotlib Span Selector

PythonPythonBeginner
Practice Now

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

Introduction

This lab will guide you through how to use the Matplotlib Span Selector to select a range on an axis and plot a detailed view of the selected range on another axis.

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 python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/InteractiveFeaturesGroup(["`Interactive Features`"]) 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/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") 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`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48949{{"`Matplotlib Span Selector`"}} matplotlib/importing_matplotlib -.-> lab-48949{{"`Matplotlib Span Selector`"}} matplotlib/figures_axes -.-> lab-48949{{"`Matplotlib Span Selector`"}} matplotlib/line_plots -.-> lab-48949{{"`Matplotlib Span Selector`"}} matplotlib/interactive_backends -.-> lab-48949{{"`Matplotlib Span Selector`"}} python/variables_data_types -.-> lab-48949{{"`Matplotlib Span Selector`"}} python/booleans -.-> lab-48949{{"`Matplotlib Span Selector`"}} python/conditional_statements -.-> lab-48949{{"`Matplotlib Span Selector`"}} python/for_loops -.-> lab-48949{{"`Matplotlib Span Selector`"}} python/lists -.-> lab-48949{{"`Matplotlib Span Selector`"}} python/tuples -.-> lab-48949{{"`Matplotlib Span Selector`"}} python/function_definition -.-> lab-48949{{"`Matplotlib Span Selector`"}} python/importing_modules -.-> lab-48949{{"`Matplotlib Span Selector`"}} python/standard_libraries -.-> lab-48949{{"`Matplotlib Span Selector`"}} python/math_random -.-> lab-48949{{"`Matplotlib Span Selector`"}} python/data_collections -.-> lab-48949{{"`Matplotlib Span Selector`"}} python/numerical_computing -.-> lab-48949{{"`Matplotlib Span Selector`"}} python/data_visualization -.-> lab-48949{{"`Matplotlib Span Selector`"}} python/build_in_functions -.-> lab-48949{{"`Matplotlib Span Selector`"}} end

Import Required Libraries

First, we need to import the required libraries - numpy and matplotlib.

import numpy as np
import matplotlib.pyplot as plt

Create Sample Data

We will now create some sample data to plot using numpy.

## Fixing random state for reproducibility
np.random.seed(19680801)

x = np.arange(0.0, 5.0, 0.01)
y = np.sin(2 * np.pi * x) + 0.5 * np.random.randn(len(x))

Create Figure and Subplots

We will now create a figure with two subplots using matplotlib.

fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 6))

Plot Data on First Subplot

We will plot the sample data on the first subplot.

ax1.plot(x, y)
ax1.set_ylim(-2, 2)
ax1.set_title('Press left mouse button and drag '
              'to select a region in the top graph')

Define a Callback Function

We will define a callback function that will be called when a range is selected using the Span Selector.

def onselect(xmin, xmax):
    indmin, indmax = np.searchsorted(x, (xmin, xmax))
    indmax = min(len(x) - 1, indmax)

    region_x = x[indmin:indmax]
    region_y = y[indmin:indmax]

    if len(region_x) >= 2:
        line2.set_data(region_x, region_y)
        ax2.set_xlim(region_x[0], region_x[-1])
        ax2.set_ylim(region_y.min(), region_y.max())
        fig.canvas.draw_idle()

Create a Span Selector

We will create a Span Selector object using matplotlib.widgets.SpanSelector.

span = SpanSelector(
    ax1,
    onselect,
    "horizontal",
    useblit=True,
    props=dict(alpha=0.5, facecolor="tab:blue"),
    interactive=True,
    drag_from_anywhere=True
)

Plot Data on Second Subplot

We will plot the detailed view of the selected range on the second subplot.

line2, = ax2.plot([], [])

Show Plot

We will now show the plot using matplotlib.pyplot.show().

plt.show()

Summary

In this lab, we learned how to use the Matplotlib Span Selector to select a range on an axis and plot a detailed view of the selected range on another axis. We also learned how to create a Span Selector object and define a callback function to handle the selected range.

Other Python Tutorials you may like