0
0
Matplotlibdata~5 mins

Pick events for data interaction in Matplotlib

Choose your learning style9 modes available
Introduction

Pick events let you click on parts of a plot to get more information or interact with the data.

You want to click on a point in a scatter plot to see its value.
You want to select bars in a bar chart to highlight them.
You want to interact with a plot to filter or update data.
You want to make your plots interactive for presentations.
You want to build simple data exploration tools.
Syntax
Matplotlib
fig.canvas.mpl_connect('pick_event', onpick)

# where onpick is a function that handles the event

The 'pick_event' triggers when you click on a pickable artist (like points or lines).

You must set the 'picker' property on plot elements to make them pickable.

Examples
This makes the line pickable with a 5-point tolerance around it.
Matplotlib
line, = plt.plot(x, y, picker=5)

# picker=5 means the click tolerance in points
Each point in the scatter plot can be clicked to trigger pick events.
Matplotlib
scatter = plt.scatter(x, y, picker=True)

# picker=True makes each point pickable
Sample Program

This code creates a scatter plot where you can click on points. When you click, it prints the point's index and coordinates.

Matplotlib
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]

fig, ax = plt.subplots()
scatter = ax.scatter(x, y, picker=True)

# Define the pick event handler
def onpick(event):
    ind = event.ind[0]  # index of the picked point
    print(f"You clicked on point {ind} with coordinates ({x[ind]}, {y[ind]})")

# Connect the pick event to the handler
fig.canvas.mpl_connect('pick_event', onpick)

plt.title('Click on a point')
plt.show()
OutputSuccess
Important Notes

Pick events only work if the plot elements have the 'picker' property set.

The event object gives you information about what was clicked, like the index of the point.

Pick events are useful for adding interactivity without complex GUI code.

Summary

Pick events let you click on plot elements to interact with data.

Set 'picker' on plot elements to make them clickable.

Use 'fig.canvas.mpl_connect' to link pick events to your handler function.