Bird
Raised Fist0
Matplotlibdata~20 mins

Mplcursors for hover labels 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
🎖️
Mplcursors Hover Label Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of mplcursors hover label code
What will be the output when running this code snippet that uses mplcursors to add hover labels to a scatter plot?
Matplotlib
import matplotlib.pyplot as plt
import mplcursors

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

cursor = mplcursors.cursor(sc)
cursor.connect("add", lambda sel: sel.annotation.set_text(f"Point: {sel.target[0]}, {sel.target[1]}"))

plt.show()
AThe code raises a NameError because mplcursors is not imported.
BA scatter plot appears. Hovering over points shows labels like 'Point: 1, 4', 'Point: 2, 5', etc.
CThe scatter plot appears but no hover labels show when hovering over points.
DThe code raises a TypeError due to incorrect lambda function syntax.
Attempts:
2 left
💡 Hint
Check how mplcursors connects to the scatter plot and sets annotation text.
🧠 Conceptual
intermediate
1:30remaining
Understanding mplcursors cursor targets
In mplcursors, what does the 'sel.target' attribute represent when handling the 'add' event for a scatter plot?
AThe x and y coordinates of the data point being hovered over.
BThe color and size of the scatter plot markers.
CThe matplotlib figure object containing the plot.
DThe index of the data point in the original dataset.
Attempts:
2 left
💡 Hint
Think about what information you want to show in a hover label.
🔧 Debug
advanced
2:30remaining
Why does this mplcursors hover label code fail?
Given this code, why does it fail to show hover labels? import matplotlib.pyplot as plt import mplcursors fig, ax = plt.subplots() sc = ax.scatter([1, 2, 3], [4, 5, 6]) cursor = mplcursors.cursor(sc) cursor.connect("add", lambda sel: sel.annotation.set_text(f"Point: {sel.target}")) plt.show()
AThe f-string tries to print 'sel.target' directly, which is an array, causing the label to be unreadable.
BThe lambda function is missing a return statement, causing a runtime error.
CThe scatter plot is missing a label parameter, so mplcursors cannot create annotations.
DThe 'connect' method is called with the wrong event name; it should be 'hover' instead of 'add'.
Attempts:
2 left
💡 Hint
Check what 'sel.target' contains and how it is formatted in the label.
data_output
advanced
1:30remaining
Number of annotations created by mplcursors
If you run mplcursors on a scatter plot with 5 points and hover over 3 different points sequentially, how many annotation objects will mplcursors create?
A1 annotation reused for all points hovered.
B5 annotations, one for each point in the scatter plot.
C0 annotations, because mplcursors does not create annotations automatically.
D3 annotations, one for each hovered point.
Attempts:
2 left
💡 Hint
Think about how mplcursors creates annotations on demand when points are hovered.
🚀 Application
expert
3:00remaining
Customizing mplcursors hover labels with additional data
You have a scatter plot with points and a list of labels: labels = ['A', 'B', 'C']. How do you modify mplcursors to show the label along with coordinates on hover?
Matplotlib
import matplotlib.pyplot as plt
import mplcursors

x = [1, 2, 3]
y = [4, 5, 6]
labels = ['A', 'B', 'C']

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

cursor = mplcursors.cursor(sc)

# Fill in the lambda function below to show label and coordinates
cursor.connect("add", lambda sel: sel.annotation.set_text(???))

plt.show()
Alambda sel: sel.annotation.set_text(f"Label: {labels[sel.annotation]}, Point: {sel.target[0]}, {sel.target[1]}")
Blambda sel: sel.annotation.set_text(f"Label: {labels[sel.target]}, Point: {sel.target[0]}, {sel.target[1]}")
Clambda sel: sel.annotation.set_text(f"Label: {labels[sel.index]}, Point: {sel.target[0]}, {sel.target[1]}")
Dlambda sel: sel.annotation.set_text(f"Label: {labels[sel]}, Point: {sel.target[0]}, {sel.target[1]}")
Attempts:
2 left
💡 Hint
Use sel.index to get the index of the hovered point to access the label list.

Practice

(1/5)
1. What is the main purpose of using mplcursors in matplotlib plots?
easy
A. To save the plot as an image file
B. To change the color of the plot lines
C. To add interactive hover labels showing data values
D. To create 3D plots automatically

Solution

  1. Step 1: Understand mplcursors functionality

    mplcursors is a tool that adds interactive hover labels to matplotlib plots, showing data values when you hover over points.
  2. Step 2: Compare options with mplcursors purpose

    Changing colors, saving images, or creating 3D plots are not related to hover labels, so only adding interactive hover labels fits.
  3. Final Answer:

    To add interactive hover labels showing data values -> Option C
  4. Quick Check:

    mplcursors = interactive hover labels [OK]
Hint: Remember mplcursors = hover labels for data points [OK]
Common Mistakes:
  • Confusing mplcursors with plot styling tools
  • Thinking mplcursors saves files
  • Assuming mplcursors creates 3D plots
2. Which of the following is the correct way to import mplcursors for use in a matplotlib plot?
easy
A. import mplcursors
B. from matplotlib import mplcursors
C. import matplotlib.mplcursors
D. import mpl_cursor

Solution

  1. Step 1: Recall correct import syntax

    The mplcursors library is a separate package and is imported simply with import mplcursors.
  2. Step 2: Check other options for errors

    from matplotlib import mplcursors is wrong because mplcursors is not part of matplotlib. import matplotlib.mplcursors is wrong because it's a separate package, not a submodule. import mpl_cursor is incorrect because the module name is mplcursors, not mpl_cursor.
  3. Final Answer:

    import mplcursors -> Option A
  4. Quick Check:

    Correct import = import mplcursors [OK]
Hint: Use simple import: import mplcursors [OK]
Common Mistakes:
  • Trying to import mplcursors from matplotlib
  • Thinking mplcursors is matplotlib.mplcursors submodule
  • Using wrong module name like mpl_cursor
3. What will be the output behavior of this code snippet?
import matplotlib.pyplot as plt
import mplcursors

fig, ax = plt.subplots()
points = ax.plot([1, 2, 3], [4, 5, 6], 'o')
mplcursors.cursor(points)
plt.show()
medium
A. Plot shows points with hover labels displaying (x, y) values
B. Plot shows points but no hover labels appear
C. Code raises an error because cursor() needs extra arguments
D. Plot shows a line connecting points without markers

Solution

  1. Step 1: Understand code components

    The code plots points at (1,4), (2,5), (3,6) with markers 'o'. Then mplcursors.cursor(points) adds interactive hover labels.
  2. Step 2: Predict output behavior

    When running plt.show(), the plot appears with points. Hovering over points shows labels with their coordinates because mplcursors is activated correctly.
  3. Final Answer:

    Plot shows points with hover labels displaying (x, y) values -> Option A
  4. Quick Check:

    mplcursors.cursor(points) = hover labels shown [OK]
Hint: mplcursors.cursor() adds hover labels to plotted points [OK]
Common Mistakes:
  • Thinking cursor() needs extra arguments
  • Expecting no hover labels without extra setup
  • Confusing line plot with marker plot
4. Identify the error in this code that prevents hover labels from showing:
import matplotlib.pyplot as plt
import mplcursors

fig, ax = plt.subplots()
line, = ax.plot([1, 2, 3], [4, 5, 6])
mplcursors.cursor(line)
plt.show()
medium
A. The variable 'line' should be a list, not a single Line2D object
B. The plot command is missing marker style to show points
C. mplcursors is not imported correctly
D. mplcursors.cursor() must be called before plotting

Solution

  1. Step 1: Analyze plot and cursor usage

    The code plots a line without markers. Hover labels appear on points, but here points are not visible because no markers are set.
  2. Step 2: Identify why hover labels don't show

    mplcursors works on plotted points. Without markers, the line is continuous and no discrete points exist to hover on, so labels don't appear.
  3. Final Answer:

    The plot command is missing marker style to show points -> Option B
  4. Quick Check:

    Missing markers = no hover labels [OK]
Hint: Add markers to plot for mplcursors hover labels [OK]
Common Mistakes:
  • Thinking mplcursors must be called before plot
  • Assuming single Line2D object is invalid input
  • Believing import error causes no labels
5. You want to show hover labels only for points where y > 5 in this plot. Which code change achieves this?
import matplotlib.pyplot as plt
import mplcursors

fig, ax = plt.subplots()
x = [1, 2, 3, 4]
y = [4, 5, 6, 7]
points = ax.plot(x, y, 'o')
# Add hover labels only for y > 5
mplcursors.cursor(points)
hard
A. Use mplcursors.cursor(points).remove() for points with y <= 5
B. Filter points before plotting: ax.plot([xi for xi, yi in zip(x,y) if yi>5], [yi for yi in y if yi>5], 'o')
C. Set cursor with mplcursors.cursor(points, hover=True, filter=lambda sel: sel.target[1] > 5)
D. Use mplcursors.cursor(points).connect('add', lambda sel: sel.annotation.set_visible(sel.target[1] > 5))

Solution

  1. Step 1: Understand how to filter hover labels

    mplcursors allows connecting to events like 'add' to customize annotation visibility based on data values.
  2. Step 2: Analyze options for filtering by y > 5

    Use mplcursors.cursor(points).connect('add', lambda sel: sel.annotation.set_visible(sel.target[1] > 5)) uses a lambda to set annotation visible only if y > 5, which is correct. Filter points before plotting: ax.plot([xi for xi, yi in zip(x,y) if yi>5], [yi for yi in y if yi>5], 'o') filters points before plotting but does not use mplcursors filtering. Set cursor with mplcursors.cursor(points, hover=True, filter=lambda sel: sel.target[1] > 5) uses a non-existent 'filter' argument. Use mplcursors.cursor(points).remove() for points with y <= 5 tries to remove cursor which is not valid for selective filtering.
  3. Final Answer:

    Use mplcursors.cursor(points).connect('add', lambda sel: sel.annotation.set_visible(sel.target[1] > 5)) -> Option D
  4. Quick Check:

    Connect 'add' event to filter hover labels [OK]
Hint: Use cursor.connect('add', lambda sel: condition) to filter labels [OK]
Common Mistakes:
  • Trying to filter points only by plotting
  • Using unsupported 'filter' argument in cursor()
  • Attempting to remove cursor for selective points