python - 非单调数据的三次样条(不是一维函数)

标签 python interpolation

我有一条曲线,如下所示:
enter image description here
此图的 x 坐标和 y 坐标为:path_x= (4.0, 5.638304088577984, 6.785456961280076, 5.638304088577984, 4.0)path_y =(0.0, 1.147152872702092, 2.7854569612800755, 4.423761049858059, 3.2766081771559668)我通过以下方式获得了上面的图片:

x_min =min(path_x)-1
x_max =max(path_x)+1
y_min =min(path_y)-1
y_max =max(path_y)+1

num_pts = len(path_x)

fig = plt.figure(figsize=(8,8))
#fig = plt.figure()
plt.suptitle("Curve and the boundary")
ax = fig.add_subplot(1,1,1)

ax.set_xlim([min(x_min,y_min),max(x_max,y_max)])
ax.set_ylim([min(x_min,y_min),max(x_max,y_max)])
ax.plot(path_x,path_y)
现在我的目的是使用三次样条绘制平滑曲线。但是对于三次样条,您需要 x coordinates 以升序排列。而在这种情况下,x valuesy values 都不是升序。
这也不是一个功能。即 x value 映射到范围内的多个元素。
我还浏览了 this 帖子。但是我想不出一个合适的方法来解决我的问题。
我真的很感谢你在这方面的帮助

最佳答案

正如评论中所建议的,您始终可以使用任意(和线性!)参数来参数化任何曲线/曲面。
例如,将 t 定义为参数,以便您获得 x=x(t)y=y(t) 。由于 t 是任意的,您可以定义它,以便在 t=0 处获得第一个 path_x[0],path_y[0] ,在 t=1 处获得最后一对坐标 path_x[-1],path_y[-1]
这是使用 scipy.interpolate 的代码

import numpy
import scipy.interpolate
import matplotlib.pyplot as plt

path_x = numpy.asarray((4.0, 5.638304088577984, 6.785456961280076, 5.638304088577984, 4.0),dtype=float)
path_y = numpy.asarray((0.0, 1.147152872702092, 2.7854569612800755, 4.423761049858059, 3.2766081771559668),dtype=float)

# defining arbitrary parameter to parameterize the curve
path_t = numpy.linspace(0,1,path_x.size)

# this is the position vector with
# x coord (1st row) given by path_x, and
# y coord (2nd row) given by path_y
r = numpy.vstack((path_x.reshape((1,path_x.size)),path_y.reshape((1,path_y.size))))

# creating the spline object
spline = scipy.interpolate.interp1d(path_t,r,kind='cubic')

# defining values of the arbitrary parameter over which
# you want to interpolate x and y
# it MUST be within 0 and 1, since you defined
# the spline between path_t=0 and path_t=1
t = numpy.linspace(numpy.min(path_t),numpy.max(path_t),100)

# interpolating along t
# r[0,:] -> interpolated x coordinates
# r[1,:] -> interpolated y coordinates
r = spline(t)

plt.plot(path_x,path_y,'or')
plt.plot(r[0,:],r[1,:],'-k')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
带输出
cubic spline in 2d

关于python - 非单调数据的三次样条(不是一维函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67460967/

相关文章:

python - 通过pipenv安装mysqlclient抛出错误

python - pytest fixture 的多个副本

python - 在 Luigi Visualiser 中保留已完成的管道

python - 动画+在矩阵之间平滑插值

python - 如何通过 Cassandra python-driver ORM 增加计数器列

python - 消除列表中的重复元素

python - 如何使用线性插值扩展数组

python - 使用Python通过矢量场进行图像变形

matlab - 如何在matlab中对波动向量进行插值?

r - 使用 interp 推断数据无法生成准确的图像