0

Hy everybody! I am a beginer in python and data analysis, and meet with a problem, during fitting a power function to my data. Here I plotted my dataset as a scatterplot

I want to plot a power function with expontent arround -1 , but after I apply the levenberg-marquardt method, using lmfit library in python, I get the following faulty image. I tried to modify the initial parameters, but it didn't help.

Here is my code:

%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from lmfit import minimize, Parameters, Parameter, report_fit
be = pd.read_table('...', 
               skipinitialspace=True,
               names = ["CoM", "slope", "slope2"])

x=be["CoM"]
data=be["slope"]




def fcn2min(params, x, data):
n2 = params['n2'].value
n1 = params['n1'].value

model = n1 * x ** n2
return model - data #that's what you want to minimize

# create a set of Parameters
# 'value' is the initial condition
params = Parameters() 
params.add('n2', value= -1.00)
params.add('n1',value= 23.0)

# do fit, here with leastsq model
result = minimize(fcn2min, params, args=(be["CoM"],be["slope"]))

#calculate final result
final = data + result.residual
resid = result.residual

# write error report
report_fit(result)

#plot results

xplot = x
yplot = result.params['n1'].value * x ** result.params['n2'].value


plt.figure(figsize=(15,6))
plt.ylabel('OD-slope',fontsize=18, color='blue')
plt.xlabel('CoM height_Sz  [m]',fontsize=18, color='blue')

plt.plot(be["CoM"],be["slope"],"o", label="slope_flat")
plt.plot(be["CoM"],be["slope2"],"+",color='r', label="slope_curv")
plt.plot(xplot,yplot)
plt.legend()

plt.savefig('plot2')

plt.show()

I don't quite understand what is the problem with this, so if you have any observations, thank you very much.

1 Answers1

0

It's a little hard to tell what the question is. t looks to me like the fit completed and gave a reasonably good fit, but you don't provide the fit statistics or report of the parameters.

If you're asking about all the green lines for the "COM" array (the best fit?), this is almost certainly because the starting x axis "height_Sz" data was not sorted to be strictly increasing. That's OK for the fit, but plotting an X-Y trace with a line expects the data to be in order.

M Newville
  • 7,486
  • 2
  • 16
  • 29