I am trying to gauss fit my data using scipy and curve fit, here is my code :
import csv
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
A=[]
T=[]
seuil=1000
range_gauss=4
a=0
pos_peaks=[]
amp_peaks=[]
A_gauss=[]
T_gauss=[]
new_A=[]
new_T=[]
def gauss(x,a,x0,sigma):
return a*np.exp(-(x-x0)**2/(2*sigma**2))
with open("classeur_test.csv",'r') as csvfile:
reader=csv.reader(csvfile, delimiter=',')
for row in reader :
A.append(float(row[0]))
T.append(float(row[1]))
npA=np.array(A)
npT=np.array(T)
for i in range(1,len(T)):
#PEAK DETECTION
if (A[i]>A[i-1] and A[i]>A[i+1]) and A[i]>seuil:
pos_peaks.append(i)
amp_peaks.append(A[i])
#GAUSSIAN RANGE
for j in range(-range_gauss,range_gauss):
#ATTENTION AUX LIMITES
if(i+j>0 and i+j<len(T)-1):
A_gauss.append(A[i+j])
T_gauss.append(T[i+j])
npA_gauss = np.array(A_gauss)
npT_gauss = np.array(T_gauss)
for i in range (0,7):
new_A.append(npA_gauss[i])
new_T.append(npT_gauss[i])
new_npA=np.array(new_A)
new_npT=np.array(new_T)
n = 2*range_gauss
mean = sum(new_npT*new_npA)/n
sigma = sum(new_npA*(new_npT-mean)**2)/n
popt,pcov = curve_fit(gauss,new_npT,new_npA,p0=[1,mean,sigma])
plt.plot(T,A,'b+:',label='data')
plt.plot(new_npT,gauss(new_npT,*popt),'ro:',label='Fit')
print ("new_npA : ",new_npA)
print ("new_npT : ",new_npT)
plt.legend()
plt.title('Fit')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
My arrays new_npT
and new_npA
are numpy arrays like this :
new_npA : [ 264. 478. 733. 1402. 1337. 698. 320.]
new_npT : [229.609344 231.619385 233.62944 235.639496 237.649536 239.659592
241.669647]
This is the result
I don't understand why I can't successfully plot the gauss curves...
Any explanations?
range_gauss
,A
andT
are… – nicoco Jul 2 '18 at 11:34