python - 如何使用 lmfit Python 绘制多个实验数据的高斯拟合
问题描述
我正在尝试为我的实验数据绘制高斯拟合。我的数据采用 csv 文件的形式,其中包含两列 x 和 y 值。目前我在文件夹中有 3 个 csv 文件。我正在使用“for”循环来读取文件夹中的 csv 文件并将 x 和 y 值存储在一个数组中。然后,我打印数组以检查是否所有数据值都存储在数组中。我正在尝试为我的数据值绘制高斯拟合。我附上了我得到的高斯拟合的片段。我想找到一种方法来为每个 csv 文件绘制一个拟合。现在我只适合所有 3 个文件,如代码段所示。我想生成 3 个这样的拟合。如果您需要更多详细信息,请告诉我。我很乐意提供。任何建议都会有帮助。我在下面附上了我的代码:
import csv
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp
import lmfit
from glob import glob
import os
from lmfit import Parameters, minimize, report_fit, Model
xData=np.array(xData)
yData=np.array(yData)
mean=sum(xData*yData)/sum(yData)
sigma=np.sqrt(sum(yData*(xData-mean)**2)/sum(yData))
def Gauss(x,I0,x0,sigma,Background):
return I0*exp((-(x-x0)**2)/(2*sigma**2))+Background
mod=Model(Gauss)
import glob
path=r'E:\Users\ConfocalUser\Documents\GitHub\qudi\NV_Points'
#path=r"E:\Users\ConfocalUser\Documents\GitHub\qudi"
files=glob.glob(os.path.join(path,'*.csv')) # add the second closing parenthesis here
xData=[]
yData=[]
for file in files:
print(file)
with open(file,"r") as f_in: ##### open 'file'
reader=csv.reader(f_in)
next(reader) ####NB only use this if CSV has a header line
for line in reader:
try:
float_1,float_2=float(line[0]),float(line[1])
xData.append(float_1)
yData.append(float_2)
except ValueError:
continue
#############################################################
#gives fit and results
#result#gives statistics
print('xData:', xData) # show the results
print('yData:', yData)
###check if the path is correct
Sample output:
E:\Users\ConfocalUser\Documents\GitHub\qudi\NV_Points\0951 x 30.csv
E:\Users\ConfocalUser\Documents\GitHub\qudi\NV_Points\0951 y 30.csv
E:\Users\ConfocalUser\Documents\GitHub\qudi\NV_Points\0951 z 30.csv
xData: [-2.010019542e-06, -1.943019542e-06, -1.876019542e-06, -1.809019542e-06, -1.742019542e-06, etc]
yData: [73313.0, 4769.0, 0.0, 7259.0, 9436.0, 13502.0, 15917.0, 22537.0, 29154.0, 38734.0 etc]
plt.plot(xData,yData,'bo',label='experimental_data')
plt.grid()
plt.show()
result=mod.fit(yData,x=xData,I0=1,x0=mean,sigma=sigma,Background=0)
result.plot()
plt.grid()
解决方案
import csv
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp
import glob
import os
from lmfit import Model
path=r'E:\Users\ConfocalUser\Documents\GitHub\qudi\NV_Points'
##create a function to iterate over a folder and###########################################
###########################################################################################
def getcsvfile():
xData=[]
yData=[]
files=glob.glob(os.path.join(path,'*.csv'))
for file in files:
with open(file,"r") as f_in:
reader=csv.reader(f_in)
next(reader)
for line in reader:
try:
float_1,float_2=float(line[0]),float(line[1])
xData.append(float_1)
yData.append(float_2)
# print('x-values for file', file,xData)
# print('y-values for file', file,yData)
except ValueError:
continue
######################### define the function you want to fit (Gaussian-fit)################################
############################################################################################################
xData=np.array(xData)
yData=np.array(yData)
mean=sum(xData*yData)/sum(yData)
sigma=np.sqrt(sum(yData*(xData-mean)**2)/sum(yData))
def Gauss(x,I0,x0,sigma,Background):
return I0*exp((-(x-x0)**2)/(2*sigma**2))+Background
##################################### Plot the fit for each of the files ###################################
############################################################################################################
mod=Model(Gauss)
result=mod.fit(yData,x=xData,I0=1,x0=mean,sigma=sigma,Background=0)
result.plot()
plt.grid()
plt.xlabel('x,y,z distribution')
plt.ylabel('PL intensity')
basename=os.path.basename(file)
plt.title(basename)
print('The fit statistics for',basename)
print(result.fit_report())#min_correl=0.25))
xData=[]
yData=[]
getcsvfile()
推荐阅读
- php - onDelete('cascade') 没有效果 Laravel 5.6
- java - 如何重定向到 Spring MVC 中的视图
- android - 带索引解析的 JSONOBJECT
- google-chrome - 由 Codeception 驱动时,Chrome 67 不显示文本
- java - 如何在 JPA 中使用不同的序列名称/身份
- mysql - 如何逐行从大表中获取数据
- ios - 如何启用 SocketRocket 日志记录
- python-3.x - 下面的python代码一开始运行良好,但是由于我使用了相同的目录,所以第二次出现循环,我需要在哪里更改以避免无限循环?
- javascript - 计算对象的百分比
- ponyorm - PonyORM 中的模式迁移