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()
上記のコードは、ポイントにカーソルを合わせたときにラベルを表示できます。複数のデータフレームと複数の散布図を使用しているときに、ポイントのラベルを表示したい。複数のデータフレームと複数の散布図を使用すると、他のデータフレームに属する他のポイントにカーソルを合わせても、1 つのデータフレーム (コードの以下の部分で言及されているもの) からのみラベルが表示されます。
mplcursors.cursor().connect(
"add", lambda sel: sel.annotation.set_text(df["name"][sel.target.index]))
2 つのデータフレームで試すコード:
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()
ありがとうございました。