Search code examples
pythonfunctioncurve-fitting

How to find crossection of hline and a function in python?


I have created a plot like in the figure below, red plot is original data, blue is a fitted function, the horizontal lines are different levels. I need to find the both intersection points with each line. do you have any suggestions ? Thanks In advance.

fitting


Solution

  • An easy way to do this numerically is to subtract the y-value of each horizontal line from your fit and then to solve the equation fit(x) - y = 0 for x. For this, scipy.optimize.fsolve can be used as follows (https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html):

    import numpy as np
    import matplotlib.pyplot as plt
    
    from scipy.optimize import fsolve # To find the zeros
    from scipy.stats import cauchy
    
    def my_fit(x):
        # dummy function for this example
        return cauchy().pdf(x)
    
    
    horizontal_lines = [0.05, 0.15, 0.25]
    colors = ['r', 'g', 'm']
    
    x = np.linspace(-5, 5, 1000)
    
    
    plt.plot(x, my_fit(x))
    plt.hlines(horizontal_lines, -5, 5, ls="--", color=colors)
    
    for i, y in enumerate(horizontal_lines):
        x0 = fsolve(lambda x: my_fit(x) - y, -1)
        x1 = fsolve(lambda x: my_fit(x) - y, 1)
        print(f"Intersection points for {y=}: {x0=} {x1=}") 
        plt.scatter(x0, my_fit(x0), color=colors[i])
        plt.scatter(x1, my_fit(x1), color=colors[i])
    

    Output:

    Intersection points for y=0.05: x0=array([-2.3165055]) x1=array([2.3165055]) 
    Intersection points for y=0.15: x0=array([-1.05927612]) x1=array([1.05927612]) 
    Intersection points for y=0.25: x0=array([-0.5227232]) x1=array([0.5227232])
    

    enter image description here