from matplotlib import pyplot as plt
import mplcursors
from pandas import DataFrame
df = DataFrame(
[("Alice", 163, 54),
("Bob", 174, 67),
("Charlie", 177, 73),
("Diane", 168, 57)],
columns=["name", "height", "weight"])
fig,ax=plt.subplots(1,1)
ax.scatter(df["height"], df["weight"])
mplcursors.cursor().connect(
"add", lambda sel: sel.annotation.set_text(df["name"][sel.target.index]))
plt.show()
Above code can display label when hovering a point; I want to display label of a point when using multiple dataframes and multiple scatter plots. When I use multiple dataframes and multiple scatter plots, it is displaying the labels from only one dataframe(whichever is mentioned in below part of the code) even when hovering over other points belonging to other dataframes.
mplcursors.cursor().connect(
"add", lambda sel: sel.annotation.set_text(df["name"][sel.target.index]))
Code to try with two dataframes:
from matplotlib import pyplot as plt
import mplcursors
from pandas import DataFrame
df = DataFrame(
[("Alice", 163, 54),
("Bob", 174, 67),
("Charlie", 177, 73),
("Diane", 168, 57)],
columns=["name", "height", "weight"])
df1 = DataFrame(
[("Alice1", 140, 50),
("Bob1", 179, 60),
("Charlie1", 120, 70),
("Diane1", 122, 60)],
columns=["name", "height", "weight"])
fig,ax=plt.subplots(1,1)
ax.scatter(df["height"], df["weight"])
ax.scatter(df1["height"], df1["weight"])
mplcursors.cursor(hover=True).connect(
"add", lambda sel: sel.annotation.set_text(df["name"][sel.target.index]))
plt.show()
Thank you.
Introducing a new attribute to the
PathCollectionthat is returned byax.scatter, we can store the names to be displayed.The code below creates an attribute
annotation_nameswhich then can be retrieved by the annotation function.PS: Here is an attempt to remove the annotation with a mouse move. There is a test whether the mouse moved more than 2 data units in x or y direction away from the target. The ideal distance might be different in your application.