Bird
Raised Fist0
Matplotlibdata~20 mins

Pick events for data interaction in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Pick Event Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output when clicking on a scatter point?

Consider the following matplotlib code that plots points and prints the index of the clicked point.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
points = ax.scatter([1, 2, 3], [4, 5, 6], picker=True)

clicked_indices = []

def on_pick(event):
    ind = event.ind[0]
    clicked_indices.append(ind)
    print(f"Clicked point index: {ind}")

fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()

If the user clicks on the point at (2, 5), what will be printed?

Matplotlib
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
points = ax.scatter([1, 2, 3], [4, 5, 6], picker=True)

clicked_indices = []

def on_pick(event):
    ind = event.ind[0]
    clicked_indices.append(ind)
    print(f"Clicked point index: {ind}")

fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()
AClicked point index: 0
BClicked point index: 1
CClicked point index: 2
DNo output, because picker=True is not enough
Attempts:
2 left
💡 Hint

Remember that the points are indexed in the order they are given in the scatter call.

data_output
intermediate
1:30remaining
What data is available in the pick event?

Given a matplotlib pick event handler:

def on_pick(event):
    print(event.artist)
    print(event.mouseevent.xdata, event.mouseevent.ydata)
    print(event.ind)

What will event.ind contain when picking a scatter plot?

Matplotlib
def on_pick(event):
    print(event.artist)
    print(event.mouseevent.xdata, event.mouseevent.ydata)
    print(event.ind)
AThe matplotlib figure object
BThe x and y coordinates of the picked point
CA list of indices of the picked points
DThe color of the picked point
Attempts:
2 left
💡 Hint

Check the documentation for pick_event attributes.

visualization
advanced
2:30remaining
Which code produces a plot that highlights picked points?

Which option correctly updates the color of a picked scatter point to red when clicked?

Matplotlib
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
sc = ax.scatter([1, 2, 3], [4, 5, 6], picker=True)

colors = ['blue', 'blue', 'blue']
sc.set_facecolors(colors)

def on_pick(event):
    ind = event.ind[0]
    colors[ind] = 'red'
    sc.set_facecolors(colors)
    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()
AUpdate colors but do not assign back to sc.set_facecolors(colors)
BChange colors[ind] to 'green' but forget to call fig.canvas.draw()
CUse sc.set_color(colors) instead of sc.set_facecolors(colors)
DThe code above
Attempts:
2 left
💡 Hint

Remember to update the scatter plot's facecolors and redraw the canvas.

🔧 Debug
advanced
2:00remaining
Why does this pick event handler not work?

Consider this code snippet:

fig, ax = plt.subplots()
points = ax.scatter([1, 2, 3], [4, 5, 6])

def on_pick(event):
    print(event.ind)

fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()

Why does clicking on points not print anything?

ABecause picker=True is missing in scatter, so points are not pickable
BBecause the event handler function is not connected properly
CBecause event.ind does not exist for scatter plots
DBecause plt.show() must be called before connecting the event
Attempts:
2 left
💡 Hint

Check the scatter call parameters.

🚀 Application
expert
3:00remaining
How to implement a pick event that toggles point visibility?

You want to click on scatter points to toggle their visibility on the plot. Which code snippet correctly implements this behavior?

Matplotlib
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
sc = ax.scatter([1, 2, 3], [4, 5, 6], picker=True)

visible = [True, True, True]

colors = ['blue', 'blue', 'blue']
sc.set_facecolors(colors)

def on_pick(event):
    ind = event.ind[0]
    visible[ind] = not visible[ind]
    colors[ind] = 'blue' if visible[ind] else 'none'
    sc.set_facecolors(colors)
    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()
AThe code above toggles visibility by changing facecolors to 'none' and back
BChange the alpha value of the point to 0 or 1 but forget to redraw the canvas
CRemove the point from the scatter data arrays and redraw
DToggle visibility by setting the point size to 0 or original size but do not update scatter
Attempts:
2 left
💡 Hint

Changing facecolors to 'none' hides points without changing data arrays.

Practice

(1/5)
1. What does setting the picker parameter on a plot element in matplotlib do?
easy
A. Removes the plot element from the figure
B. Makes the plot element respond to mouse clicks for interaction
C. Saves the plot element as an image file
D. Changes the color of the plot element

Solution

  1. Step 1: Understand the role of the picker parameter

    The picker parameter enables a plot element to detect mouse clicks or pick events.
  2. Step 2: Connect picker to interaction

    When picker is set, the element becomes clickable, allowing interaction like showing data details.
  3. Final Answer:

    Makes the plot element respond to mouse clicks for interaction -> Option B
  4. Quick Check:

    picker enables click interaction = D [OK]
Hint: picker makes plot elements clickable for interaction [OK]
Common Mistakes:
  • Confusing picker with color or style changes
  • Thinking picker saves images
  • Assuming picker removes elements
2. Which of the following is the correct way to connect a pick event handler function named on_pick to a matplotlib figure fig?
easy
A. fig.mpl_connect('pick_event', on_pick)
B. fig.connect('pick_event', on_pick)
C. fig.canvas.mpl_connect('pick_event', on_pick)
D. fig.canvas.connect('pick_event', on_pick)

Solution

  1. Step 1: Recall the correct method to connect events in matplotlib

    Events are connected using mpl_connect on the figure's canvas object.
  2. Step 2: Match the syntax for pick events

    The correct syntax is fig.canvas.mpl_connect('pick_event', handler_function).
  3. Final Answer:

    fig.canvas.mpl_connect('pick_event', on_pick) -> Option C
  4. Quick Check:

    Use fig.canvas.mpl_connect for events = A [OK]
Hint: Use fig.canvas.mpl_connect to link pick events [OK]
Common Mistakes:
  • Using fig.connect instead of fig.canvas.mpl_connect
  • Calling mpl_connect on fig instead of fig.canvas
  • Using connect instead of mpl_connect
3. Consider the code below:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
line, = ax.plot([1, 2, 3], [4, 5, 6], picker=5)
def on_pick(event):
    print(f"Picked point: {event.ind}")
fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()

What will happen when you click near the second point on the line?
medium
A. The program prints 'Picked point: [1]' indicating the second point was picked
B. Nothing happens because picker=5 is invalid
C. An error occurs because on_pick is not connected properly
D. The plot closes immediately

Solution

  1. Step 1: Understand picker=5 meaning

    Setting picker=5 means clicks within 5 points of the line points trigger pick events.
  2. Step 2: Analyze on_pick behavior on clicking second point

    Clicking near the second point triggers on_pick, printing the index of that point, which is 1 (zero-based).
  3. Final Answer:

    The program prints 'Picked point: [1]' indicating the second point was picked -> Option A
  4. Quick Check:

    picker=5 triggers pick near points = C [OK]
Hint: picker=5 allows clicks near points to trigger events [OK]
Common Mistakes:
  • Thinking picker=5 is invalid
  • Assuming event.ind is not available
  • Believing on_pick is not connected
4. The following code is intended to print the index of a picked point on a scatter plot, but it raises an error:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
sc = ax.scatter([1,2,3], [4,5,6], picker=True)
def on_pick(event):
    print(event.ind)
fig.mpl_connect('pick_event', on_pick)
plt.show()

What is the main error causing the failure?
medium
A. Calling mpl_connect on fig instead of fig.canvas
B. Using picker=True instead of a numeric tolerance
C. Not defining on_pick before connecting it
D. Using scatter instead of plot for pick events

Solution

  1. Step 1: Check how event connection is done

    The code calls fig.mpl_connect, but the correct method is fig.canvas.mpl_connect.
  2. Step 2: Understand impact of wrong connection

    Because mpl_connect is not a method of fig, this causes an AttributeError and failure.
  3. Final Answer:

    Calling mpl_connect on fig instead of fig.canvas -> Option A
  4. Quick Check:

    Use fig.canvas.mpl_connect, not fig.mpl_connect = A [OK]
Hint: Always connect events on fig.canvas, not fig [OK]
Common Mistakes:
  • Using picker=True is allowed, not an error
  • Assuming on_pick must be defined before connection
  • Thinking scatter can't use pick events
5. You want to create an interactive matplotlib scatter plot where clicking a point highlights it by changing its color. Which approach correctly combines pick events and updating the plot?
hard
A. Set picker on scatter points, connect pick_event to a function that prints point coordinates only
B. Set picker on the figure, not on points, and change colors in the handler
C. Use plt.show() inside the pick event handler to refresh the plot
D. Set picker on scatter points, connect pick_event to a function that changes the point's color and calls fig.canvas.draw()

Solution

  1. Step 1: Enable picking on scatter points

    Set the picker parameter on scatter plot points to detect clicks on them.
  2. Step 2: Update point color and redraw figure in handler

    In the pick event handler, change the color of the selected point and call fig.canvas.draw() to update the display.
  3. Final Answer:

    Set picker on scatter points, connect pick_event to a function that changes the point's color and calls fig.canvas.draw() -> Option D
  4. Quick Check:

    picker + color change + canvas.draw() = B [OK]
Hint: Change color in handler and redraw with fig.canvas.draw() [OK]
Common Mistakes:
  • Only printing coordinates without updating plot
  • Calling plt.show() inside event handler causes errors
  • Setting picker on figure instead of points