2012-04-09 31 views
4

當我繪製contourf的東西時,我會在繪圖窗口的底部看到鼠標光標下的當前x和y值。 有沒有辦法看到z值?matplotlib contourf:在光標下獲取Z值

下面的例子contourf

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

回答

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') 
+0

感謝,這是有益的,但我是問的Z值的光標下的實時顯示,同樣因爲它已經存在於X和Y. – 2012-04-11 18:05:21

+0

你不能,那是wxWidgets接口的一部分。如果您編寫自己的用戶界面,可以獲取x/y座標,將它們轉換爲座標軸上的x/y座標。既然你從plt.contour得到了輪廓,你就知道它們的輪廓,並且可以得到那個座標處或附近的輪廓。 – j13r 2012-04-11 18:22:21

+0

@AndreaZonca你確定這是你還想接受的答案嗎? [wilywampa](http://stackoverflow.com/users/752720/wilywampa)最近的[解決方案](http://stackoverflow.com/a/42054903/2749397)完全符合你的要求。 。 – gboffi 2017-02-05 17:42:24

4

顯示位置的文字遊標的n由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

它可以工作,但由於插值對於大型數據集來說也很慢(在我的情況下,它不適用於100x100網格)。 – levesque 2018-03-02 17:07:31

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