Event Handling in Matplotlib
Learn how Matplotlib handles mouse clicks, keyboard input, figure resizing, mouse movement, and other interactive events.
Event handling allows you to build interactive charts and applications that respond to user actions.
1. What is Event Handling?
Event handling is the process of detecting and responding to actions performed by a user or generated by the graphical environment.
In Matplotlib, events can occur when a user clicks on a chart, moves the mouse, presses a keyboard key, resizes a window, or closes a figure.
Common Events
- Mouse button press and release.
- Mouse movement over a figure.
- Keyboard key press and release.
- Figure resize events.
- Figure close events.
- Pick events when selecting supported plot elements.
- Draw events when a figure is rendered.
A typical event-handling flow in a Matplotlib application.
2. Connecting Events with mpl_connect()
Matplotlib provides the mpl_connect() method to
connect an event with a Python callback function.
The method is available through the figure canvas. It accepts an event name and a callback function.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.set_title("Matplotlib Event Handling")
def on_click(event):
print("Mouse click detected")
connection_id = fig.canvas.mpl_connect(
"button_press_event",
on_click
)
plt.show()
Output
When the user clicks inside the figure:
Mouse click detected
The callback function executes for each mouse button
press event received by the figure canvas.
3. Understanding the Event Object
When an event occurs, Matplotlib passes an event object to the callback function. The object contains information about the event, such as its type, location, and related figure.
| Attribute | Description |
|---|---|
event.name |
Name of the event. |
event.canvas |
Canvas associated with the event. |
event.guiEvent |
Underlying GUI event, when available. |
event.x |
Mouse x-coordinate in display pixels, when applicable. |
event.y |
Mouse y-coordinate in display pixels, when applicable. |
event.inaxes |
Axes in which the event occurred, or None. |
event.xdata |
Mouse x-coordinate in data coordinates, when available. |
event.ydata |
Mouse y-coordinate in data coordinates, when available. |
Example: Reading Mouse Coordinates
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.set_title("Click on the Plot")
def on_click(event):
if event.inaxes is not None:
print("X coordinate:", event.xdata)
print("Y coordinate:", event.ydata)
else:
print("Click occurred outside the axes")
fig.canvas.mpl_connect(
"button_press_event",
on_click
)
plt.show()
Output
Example when the user clicks inside the axes:
X coordinate: 2.35
Y coordinate: 17.50
Note: The coordinate values depend on the actual
mouse position and chart limits.
4. Handling Mouse Events
Mouse events allow an application to respond when users click or move the mouse over a figure.
| Event Name | Description |
|---|---|
button_press_event |
Triggered when a mouse button is pressed. |
button_release_event |
Triggered when a mouse button is released. |
motion_notify_event |
Triggered when the mouse moves over the canvas. |
scroll_event |
Triggered when the mouse wheel or scroll action is used. |
Example: Mouse Movement
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [5, 10, 15, 20])
ax.set_title("Move the Mouse Over the Chart")
def on_mouse_move(event):
if event.inaxes is not None:
print(
"Mouse position:",
event.xdata,
event.ydata
)
fig.canvas.mpl_connect(
"motion_notify_event",
on_mouse_move
)
plt.show()
Output
When the mouse moves over the chart:
Mouse position: 1.25 6.50
Mouse position: 1.40 7.20
Mouse position: 1.65 8.10
The values change according to the mouse position.
Example: Mouse Button Information
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 20, 30])
def on_click(event):
print("Button pressed:", event.button)
fig.canvas.mpl_connect(
"button_press_event",
on_click
)
plt.show()
Output
Example output:
Button pressed: 1
The button value depends on the mouse button
and backend event information.
5. Handling Keyboard Events
Keyboard events allow a Matplotlib application to respond when a user presses or releases a keyboard key.
| Event Name | Description |
|---|---|
key_press_event |
Triggered when a key is pressed. |
key_release_event |
Triggered when a key is released. |
Example: Detecting Keyboard Input
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.set_title("Press a Keyboard Key")
def on_key_press(event):
print("Key pressed:", event.key)
fig.canvas.mpl_connect(
"key_press_event",
on_key_press
)
plt.show()
Output
When the user presses the A key:
Key pressed: a
When the user presses the Enter key:
Key pressed: enter
Actual key names depend on the backend and key pressed.
6. Handling Pick Events
Pick events allow users to select individual graphical elements in a Matplotlib figure. They are useful when you want to detect which data point or plot object a user has selected.
To enable picking, configure the artist's picker
property.
Example: Selecting Data Points
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
fig, ax = plt.subplots()
points = ax.scatter(
x,
y,
s=100,
picker=True
)
ax.set_title("Select a Data Point")
def on_pick(event):
selected_indices = event.ind
print("Selected point indices:", selected_indices)
for index in selected_indices:
print(
"Selected coordinates:",
x[index],
y[index]
)
fig.canvas.mpl_connect(
"pick_event",
on_pick
)
plt.show()
Output
When the user selects a point:
Selected point indices: [1]
Selected coordinates: 2 20
The selected index and coordinates depend on
the point selected by the user.
7. Handling Figure Events
Figure events allow you to detect changes in the figure window, including resizing, drawing, and closing.
| Event Name | Description |
|---|---|
resize_event |
Triggered when the figure canvas is resized. |
draw_event |
Triggered after the canvas has been drawn. |
close_event |
Triggered when the figure is closed. |
Example: Figure Resize Event
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 20, 30])
ax.set_title("Resize the Figure Window")
def on_resize(event):
print("Figure resized")
fig.canvas.mpl_connect(
"resize_event",
on_resize
)
plt.show()
Output
When the figure window is resized:
Figure resized
The callback runs whenever the backend reports
a canvas resize event.
Example: Figure Close Event
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 20, 30])
def on_close(event):
print("Figure window closed")
fig.canvas.mpl_connect(
"close_event",
on_close
)
plt.show()
Output
When the figure is closed:
Figure window closed
8. Disconnecting Events
The mpl_connect() method returns a connection ID.
You can use this ID with mpl_disconnect() to
stop receiving a particular event callback.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 20, 30])
def on_click(event):
print("Mouse clicked")
connection_id = fig.canvas.mpl_connect(
"button_press_event",
on_click
)
# Disconnect the callback
fig.canvas.mpl_disconnect(connection_id)
print("Event callback disconnected")
plt.show()
Output
Event callback disconnected
The mouse click callback is no longer connected.
9. Connecting Multiple Events
A single Matplotlib figure can handle multiple event types. You can connect different callback functions to mouse, keyboard, and figure events.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.set_title("Multiple Event Handling")
def on_click(event):
print("Mouse button pressed")
def on_key(event):
print("Keyboard key:", event.key)
def on_move(event):
if event.inaxes is not None:
print("Mouse moved inside axes")
fig.canvas.mpl_connect(
"button_press_event",
on_click
)
fig.canvas.mpl_connect(
"key_press_event",
on_key
)
fig.canvas.mpl_connect(
"motion_notify_event",
on_move
)
plt.show()
Output
Possible event messages:
Mouse button pressed
Keyboard key: a
Mouse moved inside axes
Messages depend on the actions performed by the user.
10. Practical Example: Interactive Data Selection
In this example, clicking near a plotted data point displays the selected point's coordinates. The program uses a mouse event callback to identify the closest data point.
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([10, 25, 15, 30, 20])
fig, ax = plt.subplots()
points = ax.scatter(
x,
y,
color="blue",
s=100
)
ax.set_title("Click Near a Data Point")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")
def on_click(event):
if event.inaxes != ax:
return
if event.xdata is None or event.ydata is None:
return
distances = np.sqrt(
(x - event.xdata) ** 2 +
(y - event.ydata) ** 2
)
nearest_index = np.argmin(distances)
print(
"Selected point:",
(x[nearest_index], y[nearest_index])
)
fig.canvas.mpl_connect(
"button_press_event",
on_click
)
plt.show()
Output
Example when the user clicks near the point (3, 15):
Selected point: (3, 15)
The selected point depends on the user's click position.
How this example works
- NumPy arrays store the x and y coordinates.
- A scatter plot displays the data points.
- The mouse click callback receives the event object.
- The program calculates the distance from the click to each point.
np.argmin()finds the index of the nearest point.- The selected point's coordinates are printed.
11. Event Handling and Performance
Event callbacks can execute many times, especially during mouse movement. A callback that performs expensive calculations or redraws a large figure on every event can reduce application responsiveness.
Performance Recommendations
- Keep callback functions small and efficient.
- Avoid unnecessary calculations inside mouse movement callbacks.
- Do not redraw the complete figure when a small update is sufficient.
- Use
draw_idle()to request a redraw when appropriate. - Disconnect event handlers when they are no longer required.
- Use blitting for advanced interactive updates when suitable.
- Avoid printing large amounts of information for every mouse movement.
Example: Requesting a Figure Redraw
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
line, = ax.plot([1, 2, 3], [10, 20, 30])
def on_click(event):
if event.inaxes != ax:
return
line.set_color("red")
fig.canvas.draw_idle()
fig.canvas.mpl_connect(
"button_press_event",
on_click
)
plt.show()
Output
When the user clicks inside the axes:
The plotted line changes to red.
The canvas schedules a redraw to display the update.
draw_idle() requests a redraw through the GUI event
loop. It can avoid unnecessary immediate redraw operations when
multiple updates are requested close together.
12. Common Event Handling Mistakes
| Mistake | Explanation | Solution |
|---|---|---|
| Wrong event name | The callback is connected to an unsupported event name. | Use valid Matplotlib event names. |
| Missing event parameter | The callback does not accept the event object. | Define the callback with an event parameter. |
| Using coordinates without checking | Data coordinates may be None. | Check event.inaxes and coordinate values. |
| Wrong backend | The selected environment may not support GUI interaction. | Use a suitable interactive backend. |
| Callback disconnected | The callback ID was disconnected. | Verify the connection and connection ID. |
| Slow callback | Heavy operations make the chart unresponsive. | Optimize callback operations. |
13. Best Practices
- Use descriptive callback function names.
- Check the event type and event properties before processing.
- Validate mouse coordinates before performing calculations.
- Use
mpl_connect()to register event callbacks. - Store connection IDs when you may need to disconnect callbacks.
- Use an interactive backend for desktop GUI event handling.
- Keep callback operations efficient.
- Test event handling in the actual target environment.
14. Practice Questions
Beginner Level
- What is event handling in Matplotlib?
- What is the purpose of
mpl_connect()? - What is a callback function?
- Which event is triggered when a mouse button is pressed?
- What does
event.inaxesrepresent?
Intermediate Level
- Explain the difference between mouse and keyboard events.
- What information is available through the event object?
- How can you disconnect an event callback?
- What is the purpose of a pick event?
- Why should event callbacks be efficient?
Practical Tasks
- Create a line chart that prints mouse coordinates when clicked.
- Create a chart that changes its line colour when clicked.
- Write a program that detects keyboard key presses.
- Create a scatter plot that identifies selected data points.
- Connect and disconnect a mouse click event.
Summary
Event handling in Matplotlib allows charts and graphical applications to respond to user interactions such as mouse clicks, mouse movement, keyboard input, figure resizing, and window closing.
The mpl_connect() method connects an event with
a callback function. The callback receives an event object
that provides information about the event, including mouse
coordinates and the axes where the event occurred.
Matplotlib supports mouse, keyboard, pick, draw, resize,
and close events. The mpl_disconnect() method
can remove an existing event connection using its connection ID.
Efficient callback functions, suitable interactive backends, and proper event validation help create responsive and reliable interactive plotting applications.