无法将 `scipy.interpolate.RectBivariateSpline` 与 `matplotlib.pyplot,plot_surface` 一起使用

Deb*_*asu 4 python interpolation numpy scipy

我尝试构建一个最小的示例来重现我遇到的问题。请忽略随机生成的数据数组xy。我正在将非常有意义的数据输入到zSpline内部调用中plot_surface。您可以尝试将倒数第二行替换为 -surf=ax.plot_surface(xg,yg,z,rstride=1,cstride=1,cmap=cm.coolwarm,linewidth=0.1)我已将 ZSpline 替换为粗数据z。这向我表明我在语法上没有弄错。

我的代码是-

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
from scipy.interpolate import RectBivariateSpline

size=21
dat = np.random.randn(size, 2)
x=dat[:,0]
y=dat[:,1]
z=np.random.randn(size//3,size//3)
i=np.tile([1,2,3],size//3)
bool_dat=(i==1)
x_new=x[bool_dat]
y_new=y[bool_dat]
xi=np.linspace(x_new.min(),x_new.max(),size//3)
yi=np.linspace(y_new.min(),y_new.max(),size//3)

#print z.shape,xi.shape,yi.shape

zSpline = RectBivariateSpline(xi,yi,z)

xg,yg = np.meshgrid(xi,yi)
print zSpline(xg,yg)
fig=plt.figure()
ax=fig.gca(projection='3d')
surf=ax.plot_surface(xg,yg,zSpline(xg,yg),rstride=1,cstride=1,cmap=cm.coolwarm,linewidth=0.1)
plt.show()
Run Code Online (Sandbox Code Playgroud)

我得到的错误是 -

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-13-a98e6c15985e> in <module>()
     22 
     23 xg,yg = np.meshgrid(xi,yi)
---> 24 print zSpline(xg,yg)
     25 fig=plt.figure()
     26 ax=fig.gca(projection='3d')

/usr/lib/python2.7/dist-packages/scipy/interpolate/fitpack2.pyc in __call__(self, x, y, mth)
    671             z,ier = dfitpack.bispev(tx,ty,c,kx,ky,x,y)
    672             if not ier == 0:
--> 673                 raise ValueError("Error code returned by bispev: %s" % ier)
    674             return z
    675         raise NotImplementedError('unknown method mth=%s' % mth)

ValueError: Error code returned by bispev: 10
Run Code Online (Sandbox Code Playgroud)

这让我相信问题在于插值例程而不是数据/语法。关于如何进一步测试的任何建议?

编辑:为了回应告诉我问题可能来自数据类型的评论,我决定使用非随机数据进行测试。以下代码与第一个代码几乎相同 - 但无论如何我都会再次粘贴它。

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
from scipy.interpolate import RectBivariateSpline

size=21
xi=np.linspace(-np.pi,np.pi,size)
yi=np.linspace(-np.pi,np.pi,size)

xg,yg = np.meshgrid(xi,yi)
z=np.sin(xg)*np.sin(yg) #nice and smooth function
zSpline = RectBivariateSpline(xi,yi,z,kx=2,ky=2)
fig=plt.figure()
ax=fig.gca(projection='3d')
surf=ax.plot_surface(xg,yg,z,rstride=1,cstride=1,cmap=cm.coolwarm,linewidth=0.1)
#surf=ax.plot_surface(xg,yg,zSpline(xg,yg),rstride=1,cstride=1,cmap=cm.coolwarm,linewidth=0.1)
plt.show()
Run Code Online (Sandbox Code Playgroud)

这给了我以下图像作为输出。 用粗数据绘图 但是,如果使用 zSpline,则会引发错误。

EDIT2:如果我使用xg,yg = np.ogrid[-np.pi:np.pi:size*1j,-np.pi:np.pi:size*1j]而不是 meshgrid ,问题会自行解决。但我还是不知道为什么!

pv.*_*pv. 7

请参阅文档

问题是您提供给样条的 xg 和 yg 是二维数组,但例程希望它们是定义网格的一维数组(即xi,yi)。