如何在 matplotlib 中控制鼠标悬停文本

How to control mouseover text in matplotlib

当您将鼠标悬停在使用 imshow 显示的图像上时,您可以将鼠标悬停在该图像上以检查其 RGB 值。 matplotlib window(与工具栏共享space)的右下角显示了所指向像素的图像坐标和RGB值:

x = 274.99  y = 235.584  [.241, .213, .203]

但是,当我将鼠标悬停在箭袋图上时,它只显示指针的 x 和 y 坐标,而不显示所指向的 2D 向量的值。有没有办法让矢量值显示出来?

如果我只知道如何在 matplotlib 中设置那部分文本,我可以编写自定义鼠标事件处理程序 window。

有时默认情况下不存在有关颜色值的信息。事实上,我认为当前版本是基于 Whosebug 中关于该功能的一些问题出现的一些代码。

我很快找到了那两个问题:

  • matplotlib values under cursor
  • Interactive pixel information of an image in Python?

想法是更改鼠标悬停在轴上时调用的函数。此函数存储在 ax.format_coord 中。因此,一种可能的解决方案是根据输入坐标将自定义函数写入 return 所需的输出,例如像

def format_coord(x, y):
    try:
        z = # get value depending on x,y, e.g. via interpolation on grid
            # I can't fill this because the kind of data is unknown here
        return "x: {}, y: {}, z: {}".format(x,y,z)

    except:
        return "x: {}, y: {}".format(x,y)

ax.format_coord = format_coord