在Matplotlib中,您可以使用mplcursors
库来检测鼠标悬停在图例上并显示工具提示(标签/注释)。以下是如何实现这一功能的步骤:
以下是一个简单的示例,展示如何在Matplotlib中使用mplcursors
来检测鼠标悬停在图例上并显示工具提示:
import matplotlib.pyplot as plt
import mplcursors
# 创建数据
x = [1, 2, 3, 4, 5]
y1 = [10, 15, 7, 12, 9]
y2 = [5, 8, 14, 6, 11]
# 绘制图形
fig, ax = plt.subplots()
line1, = ax.plot(x, y1, label='Series 1')
line2, = ax.plot(x, y2, label='Series 2')
# 添加图例
ax.legend()
# 使用mplcursors添加交互式注释
cursor = mplcursors.cursor(hover=True)
@cursor.connect("add")
def on_add(sel):
artist = sel.artist
if isinstance(artist, plt.Line2D):
ind = sel.index
x_val = x[ind]
y_val = artist.get_ydata()[ind]
sel.annotation.set_text(f'x={x_val}, y={y_val}')
plt.show()
x
, y1
, 和y2
。matplotlib.pyplot
绘制两条线,并为每条线添加标签。ax.legend()
添加图例。mplcursors.cursor
创建一个游标对象,并设置hover=True
使其在鼠标悬停时激活。@cursor.connect("add")
定义当游标添加到某个元素时的行为,这里简单地显示该点的坐标。通过这种方式,您可以有效地在Matplotlib中实现鼠标悬停显示工具提示的功能,增强图表的交互性和信息传达效率。
领取专属 10元无门槛券
手把手带您无忧上云