Search code examples
pythonmatplotlibcurve-fitting

Fit a simple S-curve and find the midpoint in python


Let's say I have S-curved shaped data like below :

S-Curved data

I would like too find the simplest way to fit this kind of curves AND use this fit to find the midpoint (aka the point where y=0.5). The fact is that I don't know beforehand where the midpoint.

Thanks a lot for your answers,

Cheers


Solution

  • This is clearly a case of fitting a logistic curve with L=1:

    import matplotlib.pyplot as plt
    import numpy as np
    from scipy.optimize import curve_fit
    
    data = np.loadtxt(r"\data.txt", delimiter=",")
    
    x = data[:, 0]
    y = data[:, 1]
    
    
    def f(x: np.ndarray, k: float, x0: float):
        return 1 / (1 + np.exp(-k*(x - x0)))
    
    
    popt, pcov = curve_fit(f, x, y, p0 = [1, 120])
    
    fig, ax = plt.subplots(figsize=(8, 5.6))
    
    plt.scatter(x, y)
    plt.plot(x, f(x, *popt), color="red")
    plt.show()
    

    x0 is given by popt[1], i.e. 121.18.

    enter image description here