Search code examples
pythoncurve-fittingmodel-fittinglmfit

Need a smooth curve from lmfit at more datapoints


I am fitting a Lorenztian to the following data. If I plot the best fit, it only plots the results at particular values of x where I had data. I tried to get a smooth curve that is a better representation but something seems off.

data:

y_means = [2.32070822e-06, 1.90175015e-06, 2.09473380e-06, 2.80934411e-06,
   2.38255275e-06, 3.02204121e-06, 3.84290466e-06, 3.84136311e-06,
   7.53941486e-06, 8.68364774e-06, 1.20078494e-05, 2.20557048e-05,
   3.73314724e-05, 6.03141332e-05, 9.84530711e-05, 1.58565010e-04,
   3.61269554e-04, 7.53586472e-04, 3.56518897e-04, 1.60734633e-04,
   1.06442283e-04, 5.41622644e-05, 2.73085592e-05, 2.54361900e-05,
   9.10802093e-06, 4.81356192e-06, 6.49884117e-06, 4.94871197e-06,
   3.27389990e-06, 2.65197533e-06, 2.52672943e-06, 2.56496345e-06,
   2.11445845e-06, 1.96091323e-06, 2.60823301e-06]

all_xsclices = [ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
   17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
   34]

code:

# lorentzian fit
from lmfit.models import LorentzianModel

model = LorentzianModel()
params = model.guess(y_means, x=all_xslices)
all_xslices_fit = np.linspace(min(all_xslices), max(all_xslices), 100)
result = model.fit(y_means, params, x=all_xslices)
result_smooth = model.eval(x=all_xslices_fit)


# plotting the decay along y-axis: log axis
plt.figure(figsize=(8, 5), dpi=300)
plt.scatter(all_xslices, y_means, marker = '.', s = 200, c = 'g', label = "")      
# plt.plot(all_xslices,lorentzian(all_xslices,*popt), 'g', label='Lorentz 1')
plt.plot(all_xslices, result.best_fit, 'g', label='Lorentz')
plt.plot(all_xslices_fit, result_smooth, 'r', label='Lorentz')
plt.xlabel("y length", fontsize = 15)
plt.ylabel("FFT amplitude", fontsize = 15)
plt.xticks(fontsize = 15)
plt.yticks(fontsize = 15)
plt.yscale('log')
plt.subplots_adjust(right=0.96,left=0.15,top=0.96,bottom=0.12)
plt.legend(loc = 'best')
plt.show()

Here is the current result:

plot of data with fit


Solution

  • A little doc reading and trial and error and I find that what you need to do is:

    result_smooth = result.eval(x=all_xslices_fit)
    

    Reducing number of data points to make it more obvious:

    enter image description here