曲线中3个点之间的平滑曲线

曲线中3个点之间的平滑曲线

本文介绍了曲线中3个点之间的平滑曲线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在x轴上有3个数据点,在y轴上有3个数据点:

x = [1,3,5]
y=[0,5,0]

我希望一条曲线从(1,0)开始,到达(3,5)的最高点,然后在(5,0)结束

我认为我需要使用插值,但是不确定如何使用.如果我像这样使用scipy的样条线:

import bokeh.plotting as bk
from scipy.interpolate import spline
p = bk.figure()
xvals=np.linspace(1, 5, 10)
y_smooth = spline(x,y,xvals)
p.line(xvals, y_smooth)

bk.show(p)

我在(3,5)之前达到了最高点,而且看起来不平衡:

解决方案

问题是由于没有额外参数的spline的阶数为3.这意味着您没有足够的点/等式来获得样条曲线曲线(这本身表明是病态矩阵的警告).您需要应用较低阶的样条,例如三次样条,其阶数为2:

import bokeh.plotting as bk
from scipy.interpolate import spline
p = bk.figure()
xvals=np.linspace(1, 5, 10)
y_smooth = spline(x,y,xvals, order=2) # This fixes your immediate problem
p.line(xvals, y_smooth)

bk.show(p)

此外,SciPy中不推荐使用spline,因此即使有可能,也最好不要使用它.更好的解决方案是使用CubicSpline类:

import bokeh.plotting as bk
from scipy.interpolate import CubicSpline
p = bk.figure()
xvals=np.linspace(1, 5, 10)
spl = CubicSpline(x, y) # First generate spline function
y_smooth = spl(xvals) # then evalute for your interpolated points
p.line(xvals, y_smooth)

bk.show(p)

仅显示差异(使用pyplot):

可以看出,CubicSplineorder=2spline相同

I have 3 data points on the x axis and 3 on the y axis:

x = [1,3,5]
y=[0,5,0]

I would like a curved line that starts at (1,0), goes to the highest point at (3,5) and then finishes at (5,0)

I think I need to use interpolation, but unsure how. If I use spline from scipy like this:

import bokeh.plotting as bk
from scipy.interpolate import spline
p = bk.figure()
xvals=np.linspace(1, 5, 10)
y_smooth = spline(x,y,xvals)
p.line(xvals, y_smooth)

bk.show(p)

I get the highest point before (3,5) and it looks unbalanced:

解决方案

The issue is due to that spline with no extra argument is of order 3. That means that you do not have points/equations enough to get a spline curve (which manifests itself as a warning of an ill-conditioned matrix). You need to apply a spline of lower order, such as a cubic spline, which is of order 2:

import bokeh.plotting as bk
from scipy.interpolate import spline
p = bk.figure()
xvals=np.linspace(1, 5, 10)
y_smooth = spline(x,y,xvals, order=2) # This fixes your immediate problem
p.line(xvals, y_smooth)

bk.show(p)

In addition, spline is deprecated in SciPy, so you should preferably not use it, even if it is possible. A better solution is to use the CubicSpline class:

import bokeh.plotting as bk
from scipy.interpolate import CubicSpline
p = bk.figure()
xvals=np.linspace(1, 5, 10)
spl = CubicSpline(x, y) # First generate spline function
y_smooth = spl(xvals) # then evalute for your interpolated points
p.line(xvals, y_smooth)

bk.show(p)

Just to show the difference (using pyplot):

As can be seen, the CubicSpline is identical to the spline of order=2

这篇关于曲线中3个点之间的平滑曲线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 01:20