如何从高斯曲线拟合得到的结果中求解峰值对应的x轴坐标值
叠加线性背景的高斯拟合曲线峰值x值求解方案
核心注意点
你当前拟合使用的函数是高斯曲线叠加线性背景,不能直接用拟合得到的高斯中心参数mu作为总曲线的峰值x坐标,需要通过计算拟合函数的极值点得到准确结果。
完整实现代码
在你原有代码的基础上补充峰值计算逻辑即可:
import scipy as sp import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy.optimize import minimize_scalar x = sp.array([ 100., 101., 102., 103., 104., 105., 106., 107., 108., 109., 110., 111., 112., 113., 114., 115., 116., 117., 118., 119., 120., 121., 122., 123., 124., 125., 126., 127., 128., 129., 130., 131., 132., 133., 134., 135., 136., 137., 138., 139., 140., 141., 142., 143., 144., 145., 146., 147., 148., 149.]) y = sp.array([ 49.62351587, 53.28471702, 70.91469338, 59.347993 , 68.14021339, 47.96831052, 46.27111237, 47.75670421, 54.27684285, 49.79369344, 41.06072665, 43.95823631, 47.32189537, 57.59658829, 45.18881389, 56.58866369, 50.1240723 , 42.6683265 , 41.92068127, 25.85132307, 46.60808952, 38.07772697, 56.7941344 , 72.65808868, 54.94790233, 84.97532661, 82.91663574, 54.97400141, 33.05466879, 31.07916615, 30.20075973, 23.87661428, 21.81024528, 28.83273888, 17.92903416, 27.57351836, 25.05685919, 27.4866161 , 31.13142432, 20.26710321, 16.80327091, 14.1787744 , 20.52320243, 22.65700337, 16.23164708, 11.78551076, 15.21441115, 12.58749491, 12.88956241, 6.24572757]) def fit_func(x,a,mu,sig,m,c): gaus = a*sp.exp(-(x-mu)**2/(2*sig**2)) line = m*x+c return gaus + line initial_guess=[10,120,10,-2,100] po,po_cov=sp.optimize.curve_fit(fit_func,x,y,initial_guess) # 新增:计算拟合曲线峰值对应的x值 # 方法1:连续极值求解(精度更高) # 因为要找最大值,所以对fit_func取负数求最小值 def neg_fit_func(x): return -fit_func(x, po[0], po[1], po[2], po[3], po[4]) # 在x的取值范围内找最小值对应x,就是原函数的峰值x res = minimize_scalar(neg_fit_func, bounds=(x.min(), x.max()), method='bounded') peak_x_continuous = res.x print(f"连续拟合曲线峰值对应的x值:{peak_x_continuous:.3f}") # 方法2:离散点取最大值(简单直观,适合粗算) fit_y = fit_func(x, *po) peak_x_discrete = x[fit_y.argmax()] print(f"离散拟合点峰值对应的x值:{peak_x_discrete:.3f}") # 绘图 plt.plot(x, fit_y, label='Fit results') plt.errorbar(x, y, fmt='o', capsize=2) # 标记峰值点 plt.scatter(peak_x_continuous, fit_func(peak_x_continuous, *po), c='red', s=50, zorder=5, label=f'Peak x={peak_x_continuous:.2f}') plt.legend() plt.show()
输出参考
基于你提供的数据集,运行后得到的连续峰值x约为124.795,离散峰值x为125.0。
内容的提问来源于stack exchange,提问作者gemini
相关产品推荐
相关产品推荐

