我一直在努力在散点图上显示正确的信息。这是一个例子。
import matplotlib.pyplot as plt
import mplcursors
data = [
["Name1", 10, 20],
["Name2", 30, 40],
["Name3", 50, 60]
]
x_values = ["G1", "G2"]
y_values = [(row[1], row[2]) for row in data]
names = [row[0] for row in data]
fig, ax = plt.subplots()
scatter_plots = []
for i in range(len(data)):
scatter = ax.scatter(x_values, y_values[i])
scatter_plots.append(scatter)
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_title("Scatter Plot")
cursor = mplcursors.cursor(scatter_plots, hover=True)
cursor.connect("add", lambda sel: sel.annotation.set_text(names[sel.target.index]))
plt.show()
在这种情况下,当我的光标在每个图上移动(相同颜色)时,它应该显示相同的名称。然而,由于 sel.target.index 仅指示图中的 x 轴,它显示错误的名称,甚至我无法显示 Name3。我一直在寻找一种方法来处理行的鼠标悬停情况下的双数组,但还没有运气。当鼠标悬停时通过指示数组的行在每个图上显示正确的名称有什么好主意吗?
我希望显示与数据相对应的正确名称。
sel.artist
并将正确的注释与其关联起来:
import matplotlib.pyplot as plt
import mplcursors
data = [["Name1", 10, 20], ["Name2", 30, 40], ["Name3", 50, 60]]
x_values = ["G1", "G2"]
names = [row[0] for row in data]
scatter_plots = [plt.scatter(x_values, y) for y in [(row[1], row[2]) for row in data]]
# function for annotations
def cursor_annotations(sel):
"""Iterate over all plots and names, try to match it with the current selection."""
for artist, name in zip(scatter_plots, names):
if sel.artist == artist:
sel.annotation.set_text(name)
break
cursor = mplcursors.cursor(scatter_plots, hover=True)
cursor.connect("add", cursor_annotations)
plt.show()