有几种不同的方法可以解决这个问题。
你可以猴子补丁ax.format_coord,类似于this official example。我将在这里使用一种稍微“pythonic”的方法,它不依赖于全局变量。 (请注意,我假设没有指定 extent kwarg,类似于 matplotlib 示例。要完全通用,您需要执行 a touch more work。)
import numpy as np
import matplotlib.pyplot as plt
class Formatter(object):
def __init__(self, im):
self.im = im
def __call__(self, x, y):
z = self.im.get_array()[int(y), int(x)]
return 'x={:.01f}, y={:.01f}, z={:.01f}'.format(x, y, z)
data = np.random.random((10,10))
fig, ax = plt.subplots()
im = ax.imshow(data, interpolation='none')
ax.format_coord = Formatter(im)
plt.show()
或者,为了插入我自己的一个项目,您可以使用mpldatacursor。如果您指定hover=True,则只要您将鼠标悬停在已启用的艺术家上,该框就会弹出。 (默认情况下,它仅在单击时弹出。)请注意,mpldatacursor 确实可以正确处理 extent 和 origin 到 imshow 的 kwargs。
import numpy as np
import matplotlib.pyplot as plt
import mpldatacursor
data = np.random.random((10,10))
fig, ax = plt.subplots()
ax.imshow(data, interpolation='none')
mpldatacursor.datacursor(hover=True, bbox=dict(alpha=1, fc='w'))
plt.show()
另外,我忘了提到如何显示像素索引。在第一个示例中,它只是假设i, j = int(y), int(x)。如果您愿意,可以添加它们来代替 x 和 y。
使用mpldatacursor,您可以使用自定义格式化程序指定它们。 i 和 j 参数是正确的像素索引,与绘制的图像的 extent 和 origin 无关。
例如(注意图像的extent 与显示的i,j 坐标):
import numpy as np
import matplotlib.pyplot as plt
import mpldatacursor
data = np.random.random((10,10))
fig, ax = plt.subplots()
ax.imshow(data, interpolation='none', extent=[0, 1.5*np.pi, 0, np.pi])
mpldatacursor.datacursor(hover=True, bbox=dict(alpha=1, fc='w'),
formatter='i, j = {i}, {j}\nz = {z:.02g}'.format)
plt.show()