这是一个使用mplcursors 的最小示例。 hover 选项已设置,因此在悬停时调用该功能(而不是仅在单击时)。
标准显示黄色注释窗口,您可以在其中更新文本。如果您只想在状态栏中显示某些内容,则可以禁用此注释。
下面的代码显示了当鼠标悬停在曲线附近时的光标坐标。默认光标显示被禁用。
This other post 展示了 mplcursors 如何识别局部最大值的示例。
from matplotlib import pyplot as plt
import mplcursors
import numpy as np
def show_annotation(sel):
sel.annotation.set_visible(False)
fig.canvas.toolbar.set_message(f'{sel.annotation.xy[0]:.12f};{sel.annotation.xy[1]:.12f}')
fig, ax = plt.subplots()
x = np.linspace(0, 10)
ax.plot(x, np.sin(x))
fig.canvas.mpl_connect("motion_notify_event",
lambda event: fig.canvas.toolbar.set_message(""))
cursor = mplcursors.cursor(hover=True)
cursor.connect("add", show_annotation)
PS:如果只使用标准注解,可以写show_annotation如下:
def show_annotation(sel):
sel.annotation.set_text(f'x:{sel.annotation.xy[0]:.12f}\ny:{sel.annotation.xy[1]:.12f}')
在悬停模式下放大后,Mplcursors 似乎没有显示注释或状态栏更新。设置hover=False(默认模式)将导致相同的行为,但仅在单击之后(或缩放时双击)。
from matplotlib import pyplot as plt
import mplcursors
import numpy as np
def show_annotation(sel):
sel.annotation.set_visible(False)
fig.canvas.toolbar.set_message(f'{sel.annotation.xy[0]:.12f};{sel.annotation.xy[1]:.12f}')
fig, ax = plt.subplots()
x = np.linspace(0, 10)
ax.plot(x, np.sin(x))
cursor = mplcursors.cursor(hover=False)
cursor.connect("add", show_annotation)
plt.show()
要始终看到小数,而不是靠近曲线,您可以尝试以下方法(不带 mplcursors):
fig.canvas.mpl_connect("motion_notify_event",
lambda event: fig.canvas.toolbar.set_message(f"{event.xdata:.12f};{event.ydata:.12f}"))