Bird
0
0

You want to show hover labels only for points where y > 5 in this plot. Which code change achieves this?

hard📝 Application Q15 of 15
Matplotlib - Interactive Features
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)
AUse <code>mplcursors.cursor(points).remove()</code> for points with y <= 5
BFilter points before plotting: <code>ax.plot([xi for xi, yi in zip(x,y) if yi>5], [yi for yi in y if yi>5], 'o')</code>
CSet cursor with <code>mplcursors.cursor(points, hover=True, filter=lambda sel: sel.target[1] > 5)</code>
DUse <code>mplcursors.cursor(points).connect('add', lambda sel: sel.annotation.set_visible(sel.target[1] > 5))</code>
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Matplotlib Quizzes