gpt4 book ai didi

python - matplotlib imshow 从光标位置格式化

转载 作者:行者123 更新时间:2023-12-01 02:28:41 26 4
gpt4 key购买 nike

在下面的示例中,当我将光标悬停在图像上时,以及我想要在左下角显示的文本,还有相应像素的灰度值。有没有办法抑制这些信息(或格式化它)?

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()

最佳答案

可以使用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_coord 中常见的 x&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

关于python - matplotlib imshow 从光标位置格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47082466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com