Search code examples
pythonnumpymatplotlibscipysmoothing

How to smooth date based data in matplotlib?


I have a 2 lists, first with dates (datetime objects) and second with some values for these dates. When I create a simple plot:

plt.plot_date(x=dates, y=dur, fmt='r-')

I get a very ugly image like this.

How I can smooth this line? I think about extrapolation, but have not found a simple function for this. In Scipy there are very difficult tools for this, but I don't understand what I must add to my data for extrapolation.


Solution

  • You can make it smooth using sp.polyfit

    enter image description here

    Code:

    import scipy as sp
    import numpy as np
    import matplotlib.pyplot as plt
    
    # sampledata
    x = np.arange(199)
    r = np.random.rand(100)
    y = np.convolve(r, r)
    
    # plot sampledata
    plt.plot(x, y, color='grey')
    
    # smoothen sampledata using a 50 degree polynomial
    p = sp.polyfit(x, y, deg=50)
    y_ = sp.polyval(p, x)
    
    # plot smoothened data
    plt.plot(x, y_, color='r', linewidth=2)
    
    plt.show()