考虑这个y(x)函数:
我们可以在文件中生成这些散点: dataset_1D.dat
:
# x y
0 0
1 1
2 0
3 -9
4 -32
以下是这些点的1D插值代码:
-
加载此分散点
-
创建
x_mesh
-
执行1D插值
码:
import numpy as np
from scipy.interpolate import interp2d, interp1d, interpnd
import matplotlib.pyplot as plt
# Load the data:
x, y = np.loadtxt('./dataset_1D.dat', skiprows = 1).T
# Create the function Y_inter for interpolation:
Y_inter = interp1d(x,y)
# Create the x_mesh:
x_mesh = np.linspace(0, 4, num=10)
print x_mesh
# We calculate the y-interpolated of this x_mesh :
Y_interpolated = Y_inter(x_mesh)
print Y_interpolated
# plot:
plt.plot(x_mesh, Y_interpolated, "k+")
plt.plot(x, y, 'ro')
plt.legend(['Linear 1D interpolation', 'data'], loc='lower left', prop={'size':12})
plt.xlim(-0.1, 4.2)
plt.grid()
plt.ylabel('y')
plt.xlabel('x')
plt.show()
这包括以下内容:
现在,考虑这个z(x,y)函数:
我们可以在文件中生成这些散点: dataset_2D.dat
:
# x y z
0 0 0
1 1 0
2 2 -4
3 3 -18
4 4 -48
在这种情况下,我们必须执行2D插值:
import numpy as np
from scipy.interpolate import interp1d, interp2d, interpnd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Load the data:
x, y, z = np.loadtxt('./dataset_2D.dat', skiprows = 1).T
# Create the function Z_inter for interpolation:
Z_inter = interp2d(x, y, z)
# Create the x_mesh and y_mesh :
x_mesh = np.linspace(1.0, 4, num=10)
y_mesh = np.linspace(1.0, 4, num=10)
print x_mesh
print y_mesh
# We calculate the z-interpolated of this x_mesh and y_mesh :
Z_interpolated = Z_inter(x_mesh, y_mesh)
print Z_interpolated
print type(Z_interpolated)
print Z_interpolated.shape
# plot:
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x, y, z, c='r', marker='o')
plt.legend(['data'], loc='lower left', prop={'size':12})
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
这包括以下内容:
其中散点数据再次以红点显示,与2D图一致 .
- 我不知道如何解释
Z_interpolated
结果:
根据上述代码的印刷线, Z_interpolated
是形状为(10,10)的n维numpy阵列 . 换句话说,具有10行和10列的2D矩阵 .
我原本期望为 x_mesh[i]
和 y_mesh[i]
的每个值插值 z[i]
为什么我没有收到这个?
- 我怎么能在3D绘图中绘制插值数据(就像2D绘图中的黑色十字架一样)?
2 回答
您需要两个插值步骤 . 第一个在y数据之间进行插值 . 第二个插值在z数据之间 . 然后使用两个插值数组绘制
x_mesh
.在下面的完整示例中,我在y方向上添加了一些变化,以使解决方案更加通用 .
对于使用
scipy.interpolate.interp1d
,解决方案基本相同:解释
Z_interpolated
:您的1-Dx_mesh
和y_mesh
定义了mesh on which to interpolate . 因此,您的2-D插值返回z
是具有与np.meshgrid(x_mesh, y_mesh)
匹配的形状(len(y),len(x))的2D数组 . 如您所见,您的z [i,i]而不是z [i]是x_mesh[i]
和y_mesh[i]
的预期值 . 它只是有更多,网格上的所有值 .显示所有插值数据的潜在图表: