以下代码是我遇到问题的简化版本:
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata
import numpy as np
def grid(x, y, z, resX=100, resY=100):
xi = np.linspace(np.min(x), np.max(x), resX)
yi = np.linspace(np.min(y), np.max(y), resY)
#Z = griddata(x, y, z, xi, yi)
Z = griddata(x, y, z, xi, yi, interp='linear')
X, Y = np.meshgrid(xi, yi)
return X, Y, Z
data = np.random.randint(200,size = (40,20))
X = np.arange(40)
Y = np.arange(20)
x, y = np.meshgrid(X, Y)
z = np.array(data)
X, Y, Z = grid(x.ravel(), y.ravel(), z.ravel(), resX=50, resY=50)
plt.figure()
plt.subplot(1,2,1)
plt.imshow(data)
plt.subplot(1,2,2)
plt.imshow(Z)
plt.show()
只要我使用注释行
Z = griddata(x, y, z, xi, yi)
而不是
Z = griddata(x, y, z, xi, yi, interp='linear')
一切都运转良好。一旦我用线性插值启动代码,我就得到了
raise ValueError("output grid must have constant spacing"
ValueError: output grid must have constant spacing when using interp='linear'
那怎么可能,np.linspace()不会产生恒定的间距或者我错过了什么? (显然我的实际数据比示例中使用的数据复杂得多,并且间距不等,因此确实需要使用griddata!)
答案 0 :(得分:0)
升级到matplotlib 1.4.3和numpy 1.9.2就可以了。现在线性插值工作正常,但最初使用的自然邻居不再工作
raise RuntimeError("To use interp='nn' (Natural Neighbor "
RuntimeError: To use interp='nn' (Natural Neighbor interpolation) in griddata, natgrid must be installed. Either install it from http://sourceforge.net/projects/matplotlib/files/matplotlib-toolkits, or use interp='linear' instead.
我通过
升级了(Ubuntu 14.04)# Install libfreetype6-dev
sudo apt-get install libfreetype6-dev
# Upgrade to matplotlib 1.4 using PIP
sudo pip install --upgrade matplotlib
手动安装 natgrid (http://sourceforge.net/projects/matplotlib/files/matplotlib-toolkits/)后,我的所有问题都解决了!
@George:谢谢