Smoothing out curve in Python

后端 未结 2 526
北恋
北恋 2021-01-02 20:05

I have two lists of data points:

list_x = [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,         


        
相关标签:
2条回答
  • 2021-01-02 20:11

    One easy option that echoes the suggestion from Davis Herring would be to use a polynomial approximation for the data

    import numpy as np
    import matplotlib.pyplot as plt
    
    plt.figure()
    poly = np.polyfit(list_x,list_y,5)
    poly_y = np.poly1d(poly)(list_x)
    plt.plot(list_x,poly_y)
    plt.plot(list_x,list_y)
    plt.show()
    

    You would notice the oscillation at the right end of the plot that is not present in the original data which is an artifact of polynomial approximation.

    Spline interpolation as suggested above by Davis is another good option. Varying the smoothness parameter s you can achieve different balance between smoothness and distance to the original data.

    from scipy.interpolate import splrep, splev
    
    plt.figure()
    bspl = splrep(list_x,list_y,s=5)
    bspl_y = splev(list_x,bspl)
    plt.plot(list_x,list_y)
    plt.plot(list_x,bspl_y)
    plt.show()
    

    0 讨论(0)
  • 2021-01-02 20:18

    Because your data is approximate (i.e., it has been quantized), you want an approximating spline, not an interpolating spline.

    0 讨论(0)
提交回复
热议问题