Luca
Luca

Reputation: 13

Fit in python with curve_fit

I have to make a fit using curve_fit. My problem is that, instead of having a continous curve, I obtain a broken line, as shown in the figure. Here is my code:

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np  
from scipy.optimize import curve_fit

N=np.array([66851,200522,401272,801832,1200951])
e=np.array([2.88,1.75,1.17,0.80,0.71])

def er_func(x,A,c):
   return A/np.sqrt(x)+c
from scipy.optimize import curve_fit
popt, pcov=curve_fit(er_func,N,e,p0=[10,1000])
plt.plot(N,er_func(N,*popt),"b")
plt.plot(N,e,"xr")
plt.xlabel("Number of events")
plt.ylabel("Error [Chn]")

[https://i.sstatic.net/BZtnN.png][1]

I think that this happens because I'm plotting the fit function evaluated in the correspondence of my points, and then it connects the five points with a straight line. How can I obtain a correct fit? Thanks for any help you can provide.

Upvotes: 0

Views: 163

Answers (1)

Sheldore
Sheldore

Reputation: 39052

I am only showing the relevant part of the code. You needed to define a fine mesh (N_mesh below) for plotting your continuous fit curve. I am highlighting the lines added/modified by a comment

N=np.array([66851,200522,401272,801832,1200951])
N_mesh = np.linspace(N[0], N[-1], 100)  # Added (A mesh of 100 x-points)
e=np.array([2.88,1.75,1.17,0.80,0.71])

def er_func(x,A,c):
    return A/np.sqrt(x)+c
from scipy.optimize import curve_fit
popt, pcov=curve_fit(er_func,N,e,p0=[10,1000])
plt.plot(N_mesh,er_func(N_mesh,*popt),"b", label='Fit') # Modified
plt.plot(N,e,"xr", label='Actual data') # Modified
plt.legend(fontsize=14) # Added

Output

enter image description here

Upvotes: 1

Related Questions