matplotlib contourf:在光标下获取Z值

问题描述 投票:4回答:3

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

这里有一个例子contourf

import matplotlib.pyplot as plt
import numpy as hp
plt.contourf(np.arange(16).reshape(-1,4))
python plot matplotlib contour
3个回答
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')

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

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

© www.soinside.com 2019 - 2024. All rights reserved.