在 matplotlib 图上有选择地禁用 mplcursors

Selectively disable mplcursors on matplotlib plots

我目前正在使用 mplcursors 在将鼠标悬停在绘图上的一条线上时显示标签,但我有一个意想不到的结果,它在我的应用程序中的另一个绘图上显示了不需要的标签。

有什么方法可以在 1 个图上启用 mplcursors 而不是另一个图?

这就是我用来开启功能的 mplcursors.cursor(hover=True)

documentation 表示您可以使用 artists_or_axes kwarg 将 artistsaxes 作为输入 mplcursors.cursor

因此,在您的情况下,您应该只给 mplcursors.cursor 您希望在其上看到光标的 Axes 实例,而不是另一个实例。

例如,像这样的东西应该只在 ax1:

上显示光标
import matplotlib.pyplot as plt
import mplcursors

fig, (ax1, ax2) = plt.subplots(2)

ax1.plot(range(5))
ax2.plot(range(5))

mplcursors.cursor(artists_or_axes=ax1, hover=True)

plt.show()