【问题标题】:why my curve fitting plot using matplotlib looks obscured?为什么我使用 matplotlib 的曲线拟合图看起来很模糊?
【发布时间】:2021-03-02 00:36:24
【问题描述】:

我正在尝试使用 polyfit 函数进行曲线拟合。噪声数据是使用三阶多项式生成的,并且在调用 polyfit 函数时使用三阶。但是结果图中没有任何曲线元素:

import matplotlib.pyplot as plt
import numpy as np

noise_scale = 100
number_of_samples = 100
x = 25*(np.random.rand(number_of_samples,1)-0.8)
y = 5*x+20*x**2+1*x**3 + noise_scale*np.random.randn(number_of_samples,1)
xs = x.flatten()
ys = y.flatten()

p3 = np.poly1d(np.polyfit(xs, ys, 3))
plt.plot(xs,ys,'b.',xs, p3(xs),'r--')

我想知道这里做错了什么。

谢谢

【问题讨论】:

    标签: python numpy matplotlib


    【解决方案1】:

    plt.plot() 以坐标出现在xsys 数组中的顺序绘制点,并通过直线段连接连续的点。由于xs 数组中的数字是随机顺序的,这些直线段随着xs 的值的增加和减少而前后曲折。为了得到多项式函数的图,数组xs 需要从最小值到最大值进行排序。数组ys 需要相应地排序,以便点的 y 坐标仍然对应于它们关联的 x 坐标。这可以按如下方式完成:

    import matplotlib.pyplot as plt
    import numpy as np
    
    noise_scale = 100
    number_of_samples = 100
    x = 25*(np.random.rand(number_of_samples,1)-0.8)
    y = 5*x+20*x**2+1*x**3 + noise_scale*np.random.randn(number_of_samples,1)
    xs = x.flatten()
    ys = y.flatten()
    
    # sort coordinates
    s = np.argsort(xs)
    xs = xs[s]
    ys = ys[s]
    
    p3 = np.poly1d(np.polyfit(xs, ys, 3))
    plt.plot(xs,ys,'b.',xs, p3(xs),'r--')
    

    这给出了:

    【讨论】:

    • 谢谢。太好了,如果你能解释一下,为什么需要排序?
    猜你喜欢
    • 2021-03-22
    • 2022-01-24
    • 1970-01-01
    • 2016-04-16
    • 2021-11-12
    • 2018-10-17
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多