【问题标题】:How to smooth a line in python3?如何在python3中平滑一条线?
【发布时间】:2020-06-03 04:16:40
【问题描述】:

请问如何平滑这条蓝线?

import numpy as np
from matplotlib import pyplot as plt

a = [0.5365140382771445, 0.5214107372135204, 0.49844631119258076, 0.4681910992517213, 0.4310817214420628, 0.3882500155177606, 0.340292343154754, 0.2880252732908801]
b = [0.7416012836460293, 0.697385422521102, 0.6561831711375956, 0.6187959941327967, 0.585900754784896, 0.5586375446776617, 0.537388969490203, 0.5229339200070606]

time_fit = np.arange(len(b))
fitx = np.polyfit(time_fit, a, 2)
fity = np.polyfit(time_fit, b, 2)
x_fit = np.poly1d(fitx)
y_fit = np.poly1d(fity)

plt.figure(figsize=(8, 8))
plt.plot(x_fit, y_fit, c='red')
plt.plot(a, b, c = 'blue')
plt.show()

我是否用错误的多项式拟合它?

【问题讨论】:

    标签: python-3.x matplotlib smoothing


    【解决方案1】:

    因此,您正在尝试将多项式曲线拟合到您的点。让我们分解一下 2d 点的曲线拟合是如何工作的。为简单起见,我选择了二阶多项式来拟合这些点。另外,我冒昧地重命名了您的点名(a -> x 和 b ->y)。

    np.polyfit 根据您指定的顺序返回多项式系数。您可以通过将np.poly1d 应用于返回的系数来创建一个实际的多项式类。为了绘制多项式,我们拟合x 并得到z。这个(x,z) 点是我们的拟合曲线。

    import numpy as np
    from matplotlib import pyplot as plt
    
    
    x = [
        0.5365140382771445,
        0.5214107372135204,
        0.49844631119258076,
        0.4681910992517213,
        0.4310817214420628,
        0.3882500155177606,
        0.340292343154754,
        0.2880252732908801,
    ]
    y = [
        0.7416012836460293,
        0.697385422521102,
        0.6561831711375956,
        0.6187959941327967,
        0.585900754784896,
        0.5586375446776617,
        0.537388969490203,
        0.5229339200070606,
    ]
    
    # fitting x, y in a second order equation
    # this returns the coefficient of p_0*x^2 + p_1*x + p_n = 0
    # building the polynomial
    poly = np.poly1d(np.polyfit(x, y, 2))
    
    # getting the points for plotting polynomial
    z = poly(x)
    
    plt.figure(figsize=(8, 8))
    
    # scatter plotting the actual value
    plt.scatter(x, y, c="blue", marker="o", label="original points")
    
    # plotting the polynomial curve
    plt.plot(x, z, c="red", label="fitted curve (2nd order)")
    plt.legend()
    plt.show()
    

    返回,

    【讨论】:

    • 非常感谢,还有一个多项式更适合获得平滑线吗?
    • 是的,您可以尝试使用 3 阶和 4 阶多项式来拟合它。但是,您按顺序上升得越高,就会开始出现振荡。更改poly = np.poly1d(np.polyfit(x, y, 2)) 行中的顺序,看看会发生什么。这能解决您的问题吗?
    猜你喜欢
    • 1970-01-01
    • 2017-07-02
    • 2023-01-12
    • 1970-01-01
    • 2020-02-16
    • 2021-02-06
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    相关资源
    最近更新 更多