我正在用matplotlib绘制一个2D数组。在窗口的右下角显示光标的x和y坐标。如何向该状态栏添加有关光标下方数据的信息,例如,它将显示'x,y:[440,318]数据:100'而不是'x = 439.501 y = 317.744'?我可以以某种方式抓住这个导航工具栏并编写我自己的消息进行展示吗?
我设法为'button_press_event'添加了我自己的事件处理程序,以便在终端窗口上打印数据值,但这种方法只需要点击许多鼠标并充满交互式会话。
答案 0 :(得分:12)
您只需重新分配ax.format_coord
,即用于绘制该标签的回调。
请参阅文档中的this example以及 In a matplotlib figure window (with imshow), how can I remove, hide, or redefine the displayed position of the mouse?和matplotlib values under cursor
(代码直接取自示例)
"""
Show how to modify the coordinate formatter to report the image "z"
value of the nearest pixel given x and y
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
X = 10*np.random.rand(5,3)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(X, cmap=cm.jet, interpolation='nearest')
numrows, numcols = X.shape
def format_coord(x, y):
col = int(x+0.5)
row = int(y+0.5)
if col>=0 and col<numcols and row>=0 and row<numrows:
z = X[row,col]
return 'x=%1.4f, y=%1.4f, z=%1.4f'%(x, y, z)
else:
return 'x=%1.4f, y=%1.4f'%(x, y)
ax.format_coord = format_coord
plt.show()