我很难在python中插入矩阵/数据帧。
假设我有一个矩阵M = 3x4
和x = [1 3 5]
,y = [0.1 0.4 0.5 0.7]
这是我在Matlab中进行插值然后绘制的方法。
xq = 1:1:5;
yq = 0.1:0.1:1;
[xq,yq] = meshgrid(xq,yq);
zq = interp2(y,x,M,xq,yq);
figure
h=pcolor(xq,yq,zq)
set(h,'EdgeColor','none')
这是Python中的一种可能方式
from scipy import interpolate
import numpy as np
def my_interp(X, Y, Z, x, y, spn=3):
xs,ys = map(np.array,(x,y))
z = np.zeros(xs.shape)
for i,(x,y) in enumerate(zip(xs,ys)):
# get the indices of the nearest x,y
xi = np.argmin(np.abs(X[0,:]-x))
yi = np.argmin(np.abs(Y[:,0]-y))
xlo = max(xi-spn, 0)
ylo = max(yi-spn, 0)
xhi = min(xi+spn, X[0,:].size)
yhi = min(yi+spn, Y[:,0].size)
# make slices of X,Y,Z that are only a few items wide
nX = X[xlo:xhi, ylo:yhi]
nY = Y[xlo:xhi, ylo:yhi]
nZ = Z[xlo:xhi, ylo:yhi]
intp = interpolate.interp2d(nX, nY, nZ)
z[i] = intp(x,y)[0]
return z
zq = my_interp(y, x, M, xq, yq)
答案 0 :(得分:3)
正如我在评论中所指出的,使用必要的库,您的代码是1:1可以翻译成python。对于linspace
/ meshgrid
,您需要numpy
,pcolor(mesh)
需要matplotlib.pyplot
,griddata
需要scipy.interpolate
。我打算说“interp2d
is available but don't use it,但事实证明你需要在输入数据的凸包之外进行外推,因此griddata
不会削减它。这是一个interp2d
的解决方案,但是用一粒盐取得结果:
import numpy as np
import scipy.interpolate as interp
import matplotlib.pyplot as plt
# input
xv = np.array([1, 3, 5])
yv = np.array([0.1, 0.4, 0.5, 0.7])
x,y = np.meshgrid(xv,yv)
M = np.random.rand(4,3)
xqv = np.arange(1,6)
yqv = np.arange(0.1,1.1,0.1)
xq,yq = np.meshgrid(xqv,yqv)
zqfun = interp.interp2d(x,y,M)
zq = zqfun(xqv,yqv)
plt.figure()
#h = plt.pcolor(xq,yq,zq)
h = plt.pcolormesh(xq,yq,zq) # <-- same thing but faster
结果(左)与您的MATLAB原文相比较(右图;修正x,y,M
中的订单interp2d
后):
你可以看到两侧的结果不同,这是因为MATLAB总是抛弃数据的最后一行和一列,而matplotlib却没有。