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()
上面的代码可以在悬停一个点时显示标签;我想在使用多个数据框和多个散点图时显示一个点的标签。当我使用多个数据框和多个散点图时,即使将鼠标悬停在属于其他数据框的其他点上,它也仅显示一个数据框的标签(以代码下方部分中提到的为准)。
mplcursors.cursor().connect(
"add", lambda sel: sel.annotation.set_text(df["name"][sel.target.index]))
尝试使用两个数据框的代码:
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()
谢谢你。