鼠标位置调整 matplotlib imshow 的格式

3
在下面的示例中,当我将鼠标悬停在图像上时,除了我希望显示在左下角的文本外,还会显示对应像素的灰度值。有没有方法可以抑制这些信息(或格式化它)?
import numpy as np
import matplotlib.pyplot as plt

class test():
    def __init__(self):
        fig=plt.figure()
        ax=fig.add_subplot(111)
        ax.imshow(np.random.rand(20,20))
        def format_coord(x,y):
            return "text_string_made_from(x,y)"
        ax.format_coord=format_coord
        fig.canvas.draw()

请考虑提供屏幕截图,展示它的外观或应该的外观。 - Murmel
1个回答

5
一个人可以使用ax.format_coord来更改状态栏消息的xy坐标部分。

enter image description here

通过替换方法为自定义方法,
def format_coord(x,y):
    return "text_string_made_from({:.2f},{:.2f})".format(x,y)
ax.format_coord=format_coord

enter image description here

很不幸,方括号中的数据值并未由ax.format_coord提供,而是由导航工具栏的mouse_move方法设置。更糟糕的是,mouse_move是一个调用另一个方法.set_message来实际显示消息的类方法。由于工具栏依赖于后端,我们不能简单地替换它。
相反,我们需要对其进行猴子补丁,使得工具栏实例作为第一个参数传递给类方法。这使得解决方案有点繁琐。
在下面,我们有一个名为mouse_move的函数,它设置要显示的消息。这通常是来自format_coordx&y坐标。它将工具栏实例作为参数,并调用工具栏的.set_message方法。然后,我们使用另一个名为mouse_move_patch的函数,它使用工具栏实例作为参数调用mouse_move函数。mouse_move_patch函数连接到“motion_notify_event”。
import numpy as np
import matplotlib.pyplot as plt

def mouse_move(self,event):
    if event.inaxes and event.inaxes.get_navigate():
        s = event.inaxes.format_coord(event.xdata, event.ydata)
        self.set_message(s)

class test():
    def __init__(self):
        fig=plt.figure()
        ax=fig.add_subplot(111)
        ax.imshow(np.random.rand(20,20))
        def format_coord(x,y):
            return "text_string_made_from({:.2f},{:.2f})".format(x,y)
        ax.format_coord=format_coord

        mouse_move_patch = lambda arg: mouse_move(fig.canvas.toolbar, arg)
        fig.canvas.toolbar._idDrag = fig.canvas.mpl_connect(
                        'motion_notify_event', mouse_move_patch)

t = test()
plt.show()

这将导致状态栏消息中的数据值被省略。

enter image description here


我在问题中省略了关于“(或格式化)”的部分。您是否也有兴趣解决这个问题?如果是,请告诉我,但目前我不想让它变得更加复杂。 - ImportanceOfBeingErnest
完美。谢谢。 - T. Wynter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接