1

我想使用 mplcursors 在同一个工具提示上显示带有标签信息的 x 和 y 值。实际上我使用了两个光标,但框信息重叠。这是我的代码示例:

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"])

scatter1=df.plot.scatter("height", "weight")
c1=mplcursors.cursor(scatter1)

mplcursors.cursor().connect(
    "add", lambda sel: sel.annotation.set_text(df["name"][sel.target.index]))
plt.show()
4

1 回答 1

2

您可以省略第一个光标 (c1) 并将所有信息添加到另一个光标。像这样:

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"])
scatter1 = df.plot.scatter("height", "weight")
mplcursors.cursor(scatter1, hover=True).connect("add",
    lambda sel: sel.annotation.set_text(
        f'{df["name"][sel.target.index]}\nHeight: {df["height"][sel.target.index] / 100} m\nWeight: {df["weight"][sel.target.index]} kg'))
plt.show()

示例图

于 2020-01-19T03:02:22.730 回答