scipy 3D表面的插值

a9wyjsp7  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(143)

我将数据放在一个大小为21 x 30 ndarray中;它包含每个点的速度值。我制作了一个3D表面图来可视化它,但数据不是很平滑。为了对数据进行插值,以便获得平滑的峰值,我尝试了函数griddata,但似乎不起作用。
下面是我的代码:

import numpy as np
import matplotlib.pyplot as plt
vel = np.genfromtxt(r'velocity.txt')
x = np.arange(0, 21, 1)
y = np.arange(0, 30, 1)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X,Y = np.meshgrid(x, y)
surf = ax.plot_surface(x, y, vel, cmap="RdBu")
fig.set_size_inches(10, 10)
plt.show()
f0brbegy

f0brbegy1#

从问题中我可以理解,你需要做的是网格插值。使用scipy here的RegularGridInterpolator可以做到这一点。只需制作一个更精细的网格,在该网格上插值,然后绘图。

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import RegularGridInterpolator

vel=np.random.random((21,30))

# grid old

x=np.arange(0,21,1)
y=np.arange(0,30,1)
grid_old=(x,y)

# grid new

# the limits of the interpolated x and y val have to be less than the original grid

x_new=np.arange(0.1,19.9,0.1)
y_new=np.arange(0.1,28.9,0.1)
grid_new = np.meshgrid(x_new, y_new)
grid_flattened = np.transpose(np.array([k.flatten() for k in grid_new]))

# Interpolation onto a finer grid

grid_interpol = RegularGridInterpolator(grid_old,vel,method='linear')
vel_interpol = grid_interpol(grid_flattened)

# Unflatten the interpolated velocities and store into a new variable.

index=0
vel_new=np.zeros((len(x_new),len(y_new)))
for i in  range(len(x_new)):
    for j in range(len(y_new)):
        vel_new[i,j] =vel_interpol[index]
        index+=1

fig=plt.figure()
ax=fig.add_subplot(111,projection='3d')
surf=ax.plot_surface(grid_new[0],grid_new[1],vel_new.T, cmap="RdBu") 
fig.set_size_inches(10,10) 
plt.show()

相关问题