在绘制来自多个熊猫DataFrames (或来自单个DataFrame的多个子集)的数据时,我试图使用mplcur标。我读过这个问题和这一个的答案,以及这一个的答案,这与第一个答案有些多余。我能够对从DataFrame中提取数据和标签的文档的代码进行调整,使其与单个DataFrame一起使用海运,也就是说,下面的工作很好:
from matplotlib import pyplot as plt
import mplcursors
from pandas import DataFrame
import seaborn as sns
sns.set()
df = DataFrame(
[("Alice", 163, 54),
("Bob", 174, 67),
("Charlie", 177, 73),
("Diane", 168, 57)],
columns=["name", "height", "weight"])
fig, ax = plt.subplots()
sns.scatterplot(data=df, x="height", y="weight", ax=ax)
mplcursors.cursor().connect("add", lambda sel: sel.annotation.set_text(df["name"][sel.index]))第一个问题的答案代码(适用于多个DataFrames,但不使用海运)对我也很好。但是,如果我试图使它与海运一起工作,那么就不会产生游标。这是我的代码:
from matplotlib import pyplot as plt
import mplcursors
from pandas import DataFrame
import seaborn as sns
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)
# scat = ax.scatter(df["height"], df["weight"])# from the original answer
# scat1 = ax.scatter(df1["height"], df1["weight"])# from the original answer
scat = sns.scatterplot(data=df, x="height", y="weight")# my version
scat1 = sns.scatterplot(data=df1, x="height", y="weight")# my version
scat.annotation_names = [f'{n}\nh: {h}' for n, h in zip(df["name"], df["height"])]
scat1.annotation_names = [f'{n}\nw: {w}' for n, w in zip(df1["name"], df1["weight"])]
cursor = mplcursors.cursor([scat, scat1], hover=True)
cursor.connect("add", lambda sel: sel.annotation.set_text(sel.artist.annotation_names[sel.target.index]))我在木星中使用mplcursVersion0.5.1和SefernVersion0.11.2,并带有%matplotlib notebook后端。
发布于 2022-04-29 17:28:01
Matplotlib的ax.scatter返回它创建的图形元素。另一方面,Seaborn返回创建绘图的ax (子图)。(许多海运函数创建了许多不同类型的图形元素)。
在本例中,元素存储在ax.collections[0]中,用于第一次调用,ax.collections[1]存储在第二次调用中。将这些变量分配给scat和scat1变量类似于matplotlib方法。
from matplotlib import pyplot as plt
import mplcursors
from pandas import DataFrame
import seaborn as sns
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()
sns.scatterplot(data=df, x="height", y="weight", ax=ax)
sns.scatterplot(data=df1, x="height", y="weight", ax=ax)
scat = ax.collections[0]
scat1 = ax.collections[1]
scat.annotation_names = [f'{n}\nh: {h}' for n, h in zip(df["name"], df["height"])]
scat1.annotation_names = [f'{n}\nw: {w}' for n, w in zip(df1["name"], df1["weight"])]
cursor = mplcursors.cursor([scat, scat1], hover=True)
cursor.connect("add", lambda sel: sel.annotation.set_text(sel.artist.annotation_names[sel.target.index]))
plt.show()

https://stackoverflow.com/questions/72057610
复制相似问题