Scipy curve_fit: how to plot the fitted curve beyond the data points?

前端 未结 2 1085
悲哀的现实
悲哀的现实 2020-12-22 06:32

I have a number of data points and I used Scipy curve_fit to fit a curve to this data set. I now would like to plot the fit beyond the

相关标签:
2条回答
  • 2020-12-22 06:54

    You have to define an extra data range for x to extend it beyond the data range given by your data points. You can even improve the representation and calculate more x values for the fit function:

    import numpy as np
    from scipy.optimize import curve_fit
    import matplotlib.pyplot as plt
    
    def exponential_fit(x, a, b, c):
        return a*np.exp(-b*x) + c
    
    x = np.array([0, 1, 2, 3, 4, 5])
    y = np.array([30, 50, 80, 160, 300, 580])
    fitting_parameters, covariance = curve_fit(exponential_fit, x, y)
    a, b, c = fitting_parameters
    
    x_min = -4  
    x_max = 8                                #min/max values for x axis
    x_fit = np.linspace(x_min, x_max, 100)   #range of x values used for the fit function
    plt.plot(x, y, 'o', label='data')
    plt.plot(x_fit, exponential_fit(x_fit, *fitting_parameters), '-', label='Fit')
    
    plt.axis([x_min, x_max, 0, 2000])
    plt.legend()
    plt.show()
    

    For added flexibility, I introduced x_min, x_max, because the same values are used to calculate the range for x values used by the fit function and to scale the axis for the plot. numpy.linspace creates an evenly spaced sample between start and stop value, used as x values to calculate the corresponding y values in the fit function.

    0 讨论(0)
  • 2020-12-22 07:05

    x ranges from 0 to 5. If you want the curve to go up to 8 (or up to eleven) you need to supply an array which ranges to eleven... sorry 8.

    x_new = np.linspace(0,11)
    plt.plot(x_new, exponential_fit(x_new, *fitting_parameters), '-', label='Fit')
    
    0 讨论(0)
提交回复
热议问题