matplotlib contourf:在光标下获取Z值

时间:2012-04-09 23:21:33

标签: python plot matplotlib contour

当我使用contourf绘制内容时,我会在绘图窗口的底部看到鼠标光标下的当前x和y值。 有没有办法看到z值?

这是一个示例contourf

import matplotlib.pyplot as plt
import numpy as hp
plt.contourf(np.arange(16).reshape(-1,4))

3 个答案:

答案 0 :(得分:5)

显示光标位置的文本由ax.format_coord生成。您可以覆盖该方法以显示z值。例如,

import matplotlib.pyplot as plt
import numpy as np
import scipy.interpolate as si
data = np.arange(16).reshape(-1, 4)
X, Y = np.mgrid[:data.shape[0], :data.shape[1]]
cs = plt.contourf(X, Y, data)


def fmt(x, y):
    z = np.take(si.interp2d(X, Y, data)(x, y), 0)
    return 'x={x:.5f}  y={y:.5f}  z={z:.5f}'.format(x=x, y=y, z=z)


plt.gca().format_coord = fmt
plt.show()

答案 1 :(得分:2)

documentation example显示了如何将z值标签插入到情节中

脚本:http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/contour_demo.py

基本上,它是

plt.figure()
CS = plt.contour(X, Y, Z) 
plt.clabel(CS, inline=1, fontsize=10)
plt.title('Simplest default with labels')

答案 2 :(得分:0)

只是wilywampa的答案的变体。如果您已经预先计算了插值轮廓值网格,因为您的数据稀疏或者您有大量数据矩阵,这可能适合您。

import matplotlib.pyplot as plt
import numpy as np

resolution = 100
Z = np.arange(resolution**2).reshape(-1, resolution)
X, Y = np.mgrid[:Z.shape[0], :Z.shape[1]]
cs = plt.contourf(X, Y, Z)

Xflat, Yflat, Zflat = X.flatten(), Y.flatten(), Z.flatten()
def fmt(x, y):
    # get closest point with known data
    dist = np.linalg.norm(np.vstack([Xflat - x, Yflat - y]), axis=0)
    idx = np.argmin(dist)
    z = Zflat[idx]
    return 'x={x:.5f}  y={y:.5f}  z={z:.5f}'.format(x=x, y=y, z=z)

plt.colorbar()
plt.gca().format_coord = fmt
plt.show()

例如:

Example with mouse cursor