mplcursors show data when hover and/or when clicked on datapoint

Question:

is it possible for mplcursors to show data when hover over data point and also when clicked on it on the same plot?i have tried to set both but did not work.

below example have 2 plots; first plot have mplcursors to display annotation when when clicked on data point. second plot have mplcursors to display annotation when when hover on data point. dwesired outcome is to have both mplcursors behaviors (display annotation when when hover and when clikced) on same plot.
Also is it possible for one scatter1 to have different mplcursors behavior than scatter2.

import matplotlib.pyplot as plt
import mplcursors

x1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
x2 = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

#first plot
fig, ax = plt.subplots()
ax.set_title("Multiple draggable annotations")
scatter1 = ax.scatter(x1,x1)
scatter2 = ax.scatter(x2,x2)
mplcursors.cursor(multiple=True).connect("add", lambda sel: sel.annotation.draggable(True))
plt.show()


#second plot
fig, ax = plt.subplots()
ax.set_title("Hover on point annotations")
scatter1 = ax.scatter(x1,x1)
scatter2 = ax.scatter(x2,x2)
mplcursors.cursor(hover=True)
plt.show()

Asked By: Hannibal

||

Answers:

You can have multiple mplcursors active at the same time. To reduce confusion, you can change the background color for one of them.

The hover= parameter supports three modes:

  • False / NoHover: nothing happens when hovering
  • True / Persistent: the annotation pops up when hovering and stays visible until hovering over another element
  • Transient: the annotation pops up when hovering, but disappears when hovering away

The default persistent mode can be confusing when mixed with the permanent annotations.

Example code:

import matplotlib.pyplot as plt
import mplcursors

x1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
x2 = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

fig, ax = plt.subplots()
ax.set_title("Hover to see coordinates. Left click tonpersist and drag. Right click to remove.")
scatter1 = ax.scatter(x1, x1)
scatter2 = ax.scatter(x2, x2)

cursor1 = mplcursors.cursor(multiple=True)
cursor1.connect("add", lambda sel: sel.annotation.draggable(True))

cursor2 = mplcursors.cursor(hover=mplcursors.HoverMode.Transient)
cursor2.connect("add", lambda sel: sel.annotation.set_backgroundcolor('pink'))

plt.show()

two mplcursors hover and drag

Answered By: JohanC
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.