【问题标题】:How to increase the number of digits of x and y coordinates shown?如何增加显示的 x 和 y 坐标的位数?
【发布时间】:2020-04-18 19:15:57
【问题描述】:

使用 matplotlib 中的%matplotlib notebook 得到绘图

如何增加xy坐标中小数点后的位数,在我的鼠标经过图形后显示?

谢谢。

【问题讨论】:

  • 使用mplcursors,您可以轻松创建自己的悬停注释,您可以在其中控制位数和任何额外信息。
  • 谢谢@JohanC!有没有另一种方法可以在不安装的情况下增加数字,因为我没有在本地机器上使用 jupyter-notebook,而是在“云”中使用 :)
  • source code 只是几个文件。您可以将它们直接复制到您的“云”中。
  • 好的@JohanC 我做到了,我在哪里可以在xy 坐标上添加数字:)
  • mplcursors.cursor() 是否有一些参数要添加?

标签: python matplotlib jupyter-notebook mplcursors


【解决方案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}"))

【讨论】:

  • 太棒了!谢谢你:)
  • 嗨@JohanC 我在上面的代码中使用了%matplotlib notebook,然后我放大了图表上的一个点,但我不再增加位数。你有另一种方法来放大一个点而不会丢失添加的数字吗?谢谢。
  • 实际上,只需单击与缩放相对应的方形按钮,在没有缩放之后,我注意到添加的数字不再存在,并且对于两个代码(原始代码和编辑代码)都会发生这种情况)。很抱歉打扰了。
  • 点击缩放按钮让您进入缩放模式。然后缩放模式接管状态栏。从那时起,您需要双击查看扩展精度。
  • 经过一些实验,我想出了一个没有 mplcursors 的解决方案。它对你有用吗?
猜你喜欢
  • 2019-11-06
  • 2011-02-24
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多