2017-03-03 128 views
3

当使用imshow()时,鼠标指针的z值显示在屏幕截图中所示的状态行中(右侧): screenshot imshow and pcolormesh
如何通过pcolormesh()实现相同的行为?通过以下的代码生成用matplotlib的pcolormesh()在状态行中显示鼠标指针位置的z值

图像:

import numpy as np 
import matplotlib.pyplot as plt 

t = np.linspace(-1, 1, 101) 
X, Y = np.meshgrid(t, 2*t) 
Z = np.sin(2*np.pi*(X**2+Y**2)) 
fig, axx = plt.subplots(1, 2) 
axx[0].set_title("imshow()") 
axx[0].imshow(Z, origin='lower', aspect='auto', extent=[-1, 1, -2, 2]) 
axx[1].set_title("pcolormesh()") 
axx[1].pcolormesh(X, Y, Z) 
fig.tight_layout() 
plt.show() 

回答

1

一个想法是猴子修补ax.format_coord函数为包括所希望的值。这也在a matplotlib example中显示。

现在,如果你想让这两个图共享相同的功能,需要花一点点工作来获得正确的轴限制。

import numpy as np 
import matplotlib.pyplot as plt 

t = np.linspace(-1, 1, 101) 
X, Y = np.meshgrid(t, 2*t) 
Z = np.sin(np.pi*(X**2+Y**2)) 


fig, axx = plt.subplots(1, 2) 

axx[0].set_title("imshow()") 
extent = [-1-(t[1]-t[0])/2., 1+(t[1]-t[0])/2., -2-(t[1]-t[0]), 2+(t[1]-t[0])] 
axx[0].imshow(Z, origin='lower', aspect='auto', extent=extent) 

axx[1].set_title("pcolormesh()") 
axx[1].pcolormesh(X-(t[1]-t[0])/2., Y-(t[1]-t[0]), Z) 
axx[1].set_xlim(-1-(t[1]-t[0])/2., 1+(t[1]-t[0])/2.) 
axx[1].set_ylim(-2-(t[1]-t[0]), 2+(t[1]-t[0])) 

def format_coord(x, y): 
    x0, x1 = axx[1].get_xlim() 
    y0, y1 = axx[1].get_ylim() 
    col = int(np.floor((x-x0)/float(x1-x0)*X.shape[1])) 
    row = int(np.floor((y-y0)/float(y1-y0)*Y.shape[0])) 
    if col >= 0 and col < Z.shape[1] and row >= 0 and row < Z.shape[0]: 
     z = Z[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) 

axx[1].format_coord = format_coord 


fig.tight_layout() 
plt.show() 

enter image description here

+0

感谢,这正是我一直在寻找。 – Dietrich