1

使用%matplotlib notebookin matplotlib 我们得到了情节

阴谋

x如何增加和坐标中小数点后的位数y,将鼠标移到图形上后显示?

谢谢你。

4

1 回答 1

1

这是一个使用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}"))
于 2020-04-18T21:53:30.200 回答