Matplotlib Event Handling Tutorial

PythonPythonBeginner
Practice Now

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

Introduction

This lab is a step-by-step tutorial on how to connect events in one window, for example, a mouse press, to another figure window in Python Matplotlib.

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/AdvancedTopicsGroup(["`Advanced Topics`"]) 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/scatter_plots("`Scatter Plots`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/event_handling("`Event Handling`") 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/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-49039{{"`Matplotlib Event Handling Tutorial`"}} matplotlib/importing_matplotlib -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} matplotlib/figures_axes -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} matplotlib/scatter_plots -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} matplotlib/event_handling -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} python/variables_data_types -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} python/booleans -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} python/conditional_statements -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} python/for_loops -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} python/tuples -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} python/function_definition -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} python/importing_modules -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} python/standard_libraries -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} python/math_random -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} python/data_collections -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} python/numerical_computing -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} python/data_visualization -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} python/build_in_functions -.-> lab-49039{{"`Matplotlib Event Handling Tutorial`"}} end

Set up the environment

First, we need to set up the Python environment and import the necessary libraries.

import matplotlib.pyplot as plt
import numpy as np

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

figsrc, axsrc = plt.subplots(figsize=(3.7, 3.7))
figzoom, axzoom = plt.subplots(figsize=(3.7, 3.7))
axsrc.set(xlim=(0, 1), ylim=(0, 1), autoscale_on=False,
          title='Click to zoom')
axzoom.set(xlim=(0.45, 0.55), ylim=(0.4, 0.6), autoscale_on=False,
           title='Zoom window')

x, y, s, c = np.random.rand(4, 200)
s *= 200

axsrc.scatter(x, y, s, c)
axzoom.scatter(x, y, s, c)

Define the on_press function

Next, we define a function called on_press that will adjust the z and y limits of the second window based on the location of a mouse click in the first window.

def on_press(event):
    if event.button != 1:
        return
    x, y = event.xdata, event.ydata
    axzoom.set_xlim(x - 0.1, x + 0.1)
    axzoom.set_ylim(y - 0.1, y + 0.1)
    figzoom.canvas.draw()

Connect the event to the function

Now, we connect the button press event in the first window to the on_press function we just defined.

figsrc.canvas.mpl_connect('button_press_event', on_press)

Display the plot

Finally, we display the plot to the user.

plt.show()

Summary

In this lab, we learned how to connect events in one window, for example, a mouse press, to another figure window in Python Matplotlib. We also learned how to define a function to adjust the limits of the second window based on the location of a mouse click in the first window, and how to connect the button press event to this function.

Other Python Tutorials you may like