各位大佬,我这里有个关于python高斯多峰拟合的问题,希望各位帮帮忙
"""我希望读取数据文件PL.txt,画出图,然后对其中的非对称峰进行高斯多峰拟合,不知道哪里有问题,无法拟合出来,但我用origin可以较容易的得到拟合结果,希望各位大佬帮帮忙"""
PL.rar
(13.05 KB)
import numpy as np
import matplotlib.pyplot as plt
import sys
import math
from scipy.optimize import curve_fit
f=open("PL.txt","r")
line=f.readlines()
i=0
x_data=[]
y_data=[]
while i<len(line):
x=float(line[i].split()[0])
y=float(line[i].split()[1])
if (x>=500) & (x<=575): #delet later
x_data.append(x)
y_data.append(y)
else:
pass
i=i+1
#plt.plot(x_data,y_data,"b-")
def gauss_fitting(x,A1,b1,w1,d1,A2,b2,w2,d2):
y1=(A1/(w1*math.sqrt(math.pi/2)))*np.exp(-2*((x-b1)/w1)**2)+d1
y2=(A2/(w2*math.sqrt(math.pi/2)))*np.exp(-2*((x-b2)/w2)**2)+d2
return y1+y2
'''
def gauss(x,A,b,w,d): # something wrong in the similar case
y=(A/(w*math.sqrt(math.pi/2)))*np.exp(-2*((x-b)/w)**2)+d
return y
'''
popt,pcov=curve_fit(gauss_fitting,x_data,y_data,p0=[450000,530,8,0,600000,530,22,0],
bounds=([0,min(x_data),0,0,0,min(x_data),0,0],
[None,max(x_data),100,max(y_data),None,max(x_data),100,max(y_data)]))
x_fit=np.linspace(min(x_data),max(x_data),10000)
print(popt)
x=np.array(x_fit)
y1=(popt[0]/(popt[2]*math.sqrt(math.pi/2)))*np.exp(-2*((x-popt[1])/popt[2])**2)+popt[3]
y2=(popt[4]/(popt[6]*math.sqrt(math.pi/2)))*np.exp(-2*((x-popt[5])/popt[6])**2)+popt[7]
plt.plot(x,y1,"r--")
#plt.plot(x,y2,"")
plt.show()