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

我尝试构建一个最小的示例来重现我遇到的问题。请忽略随机生成的数据数组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()

我得到的错误是-

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

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

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

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

这给了我下面的图像作为输出。

但是,如果使用zSpline,则会引发错误。

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

python大神给出的解决方案

请参见the documentation。

问题是您给样条曲线的xg和yg是2D数组,但是例程希望它们是定义网格的1D数组(即xi,yi)。