2

下面是使用两列注释的散点图的代码,用mplcursors第三列标记点。

如何从单个数据框中的两列中选择两个值作为单个文本框中的注释文本?

当而不是仅"name"在注释文本框中,我希望两者都"height"显示"name"在注释文本框中。使用df[['height', 'name']]不起作用。

否则如何实现?

df = pd.DataFrame(
    [("Alice", 163, 54),
     ("Bob", 174, 67),
     ("Charlie", 177, 73),
     ("Diane", 168, 57)],
    columns=["name", "height", "weight"])

df.plot.scatter("height", "weight")
mplcursors.cursor(multiple = True).connect("add", lambda sel: sel.annotation.set_text((df["name"])[sel.target.index]))
plt.show()
4

1 回答 1

1
  • df.loc[sel.target.index, ["name", 'height']].to_string():正确选择列和行,.loc然后创建string一个.to_string()
  • 测试于python 3.8, matplotlib 3.4.2, pandas 1.3.1, 和jupyterlab 3.1.4
from mplcursors import cursor
import matplotlib.pyplot as plt
import pandas as pd

# for interactive plots in Jupyter Lab, use the following magic command, otherwise comment it out
%matplotlib qt 

df = pd.DataFrame([('Alice', 163, 54), ('Bob', 174, 67), ('Charlie', 177, 73), ('Diane', 168, 57)], columns=["name", "height", "weight"])

ax = df.plot.scatter("height", "weight")
cr = cursor(ax, hover=True, multiple=True)

cr.connect("add", lambda sel: sel.annotation.set_text((df.loc[sel.target.index, ["name", 'height']].to_string())))
plt.show()

在此处输入图像描述

于 2021-08-16T17:32:21.300 回答