用几个元素组成的矢量来平滑曲线? [英] Smoothing a curve with vectors made by few elements?

查看:17
本文介绍了用几个元素组成的矢量来平滑曲线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4条曲线由这些向量表示:

x = [300, 700, 1000, 1500]
y1 = [-1.0055394199673442, -0.11221578805214968, -1.502661406039569, 1.0216939169819494]
y2 = [-1.0200777228890747, -0.6951505674297687, -2.832988761335546, 1.0253075071285915]
y3 = [2.0502387421569463, -1.3363305947335058, 0.2893545237634795, 0.8692051683379767]
y4 = [1.8676528391899183, -1.7554177636905024, 0.2364994810496486, 0.9811885784744991]

当我绘制它们时,得到的结果如下所示:

如你所见,这些向量的几个值导致这些曲线呈之字形,我希望它们更平滑。我尝试了不同的方法,包括在Python和MatLab中。例如,在Python中,我使用了这样的NumPy方法:

xp = np.linspace(300,1500,100,endpoint=True)
z1 = np.polyfit(x,  y1, 3)
p1 = np.poly1d(z1)
z2 = np.polyfit(x, y2, 3)
p2 = np.poly1d(z2)
z3 = np.polyfit(x,y3, 3)
p3 = np.poly1d(z3)
z4 = np.polyfit(x, y4, 3)
p4 = np.poly1d(z4)

我得到了这个:

但在这种情况下,我不确定x向量之间的值是否存在极小值和极大值点。 另外,我用不同的平滑值尝试了MatLab中的&Smooth&Quot;函数,但它们也改变了向量内部的值,这些值不再像原来的值,即它们对于我想解释的概念来说是没有意义的。 我只想把剧情的曲折部分弄平一点,让曲线看起来更舒服一点……你能帮我吗?对我来说,Python或MatLab是一样的,我对任何事情都持开放态度!:)

推荐答案

好吧,我在这里建议的是作弊和捏造数据,但至少这会让曲线看起来更像你(或你的主管)想要的。

x =  [300,      700,      1000,       1500] # your original x
x2 = [300, 500, 700, 850, 1000, 1250, 1500] # add points in between

# interpolate your data for the new points in x2
p1 = np.interp(x2,x,y1)
p2 = np.interp(x2,x,y2)
p3 = np.interp(x2,x,y3)
p4 = np.interp(x2,x,y4)

# cubic spline interpolation on xp, so it looks smooth
p1 = scipy.interpolate.CubicSpline(x2,p1)
p2 = scipy.interpolate.CubicSpline(x2,p2)
p3 = scipy.interpolate.CubicSpline(x2,p3)
p4 = scipy.interpolate.CubicSpline(x2,p4)

如下所示:

如果您对外观不满意,可以在x2中尝试不同的值。

编辑:

以下是生成该图的完整代码:

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

x =  [300,      700,      1000,       1500] # your orginial x
x2 = [300, 500, 700, 850, 1000, 1250, 1500] # add points in between
xp = np.linspace(300,1500,100,endpoint=True) # your x-axis for smooth curve plot

# your orginal data
y1 = [-1.0055394199673442, -0.11221578805214968, -1.502661406039569, 1.0216939169819494]
y2 = [-1.0200777228890747, -0.6951505674297687, -2.832988761335546, 1.0253075071285915]
y3 = [2.0502387421569463, -1.3363305947335058, 0.2893545237634795, 0.8692051683379767]
y4 = [1.8676528391899183, -1.7554177636905024, 0.2364994810496486, 0.9811885784744991]

for yi in [y1,y2,y3,y4]:
    # Piecewise linear interpolation of data y over the points x2
    y_interpolated_over_x2 = np.interp(x2,x,yi)

    # Make a cubic spline from the manipulated data
    y_cubic_spline = CubicSpline(x2, y_interpolated_over_x2)

    # The smooth curve is the cubic spline evaluated at points xp
    y_smooth = y_cubic_spline(xp)

    plt.plot(xp, y_smooth) # plot the smooth curve
    plt.scatter(x, yi) # plot the original data points

plt.show()

这篇关于用几个元素组成的矢量来平滑曲线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆