如何使用 mplcursors 注释多列
How to annotate with multiple columns using mplcursors
下面是使用 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()
df.loc[sel.target.index, ["name", 'height']].to_string()
:使用 .loc
正确地 select 列和行,然后使用 .to_string()
创建一个 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()
下面是使用 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()
df.loc[sel.target.index, ["name", 'height']].to_string()
:使用.loc
正确地 select 列和行,然后使用.to_string()
创建一个 - 在
python 3.8
、matplotlib 3.4.2
、pandas 1.3.1
和jupyterlab 3.1.4
中测试
string
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()