Search code examples
pythonscipyregressiondata-fittingscipy-optimize

Fit data with scipy


I have two datasets, calculated from different equations, now I would like to fit both datasets to the same trend line, or to fit one dataset to another. I would like to constrain the blue dataset, with the orange dataset and to get the red trendline, I was wondering if I could use SciPy (scipy.optimize.leastsq or scipy.optimize.curve_fit) but I don't know how, and I don't understand the instruction, because they ask for a function as input, and this is exactly what I want, the function, I have the points (x,y). enter image description here


Solution

  • You can do this using numpy.polynomial.polynomial by fitting a second-degree polynomial to your data which uses a least-squares method.

    import numpy as np
    import numpy.polynomial.polynomial as poly
    import matplotlib.pyplot as plt
    
    x = [1, 2, 3] # --> assuming your x-data
    y = [0.1, 1, 10] # --> assuming your y-data
    
    coefs = poly.polyfit(x, y, 2)
    ffit = poly.Polynomial(coefs)
    x_new = np.linspace(1, 3, 10) # --> more data points for a smooth curve
    
    plt.plot(x, y, label="Data")
    plt.plot(x_new, ffit(x_new), label="Fit")
    plt.legend()
    plt.show()
    

    Just replace x, y, and x_new with your desired values.