我正在使用Luis发布的代码作为对此问题(Fitting a better gaussian to data points?)的答案,并且成功运行了该代码并将高斯曲线拟合到示例数据。但是,当我尝试对数据进行同样的操作(试图拟合直方图)时,我永远都不会得到曲线-仅直方图。感谢您对查找问题/错误的帮助。
data.csv可以在这里https://ufile.io/qg2nmkpe
下载from scipy.optimize import curve_fit
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
my_data = pd.read_csv("data.csv")
my_data = my_data['data'].tolist()
if (True): #True for example data, False for my dataset
angles = [-8, -6, -4, -2, 0, 2, 4, 6, 8]
data = [99, 610, 1271, 1804, 1823, 1346, 635, 125, 24]
plt.plot(angles, data, "ob", label="Measured")
else:
data, bins, _ = plt.hist(my_data, bins=60, alpha=0.5)
angles = [0.5 * (bins[r] + bins[r + 1]) for r in range(len(bins) - 1)] # center points of bins
data = list(data) # heights of bins
xlims = [min(angles), max(angles)]
angles = np.array(angles)
data = np.array(data)
n = len(data) ## <---
mean = sum(data * angles) / n
sigma = np.sqrt(sum(data * (angles - mean) ** 2) / n)
def gaus(x, a, mu, sigma):
return a * np.exp(-(x - mu) ** 2 / (2 * sigma ** 2))
popt, pcov = curve_fit(gaus, angles, data) # ,p0=[0.18,mean,sigma]) ## <--- leave out the first estimation of the parameters
x = np.linspace(xlims[0], xlims[1], 60) ## <--- calculate against a continuous variable
plt.plot(x, gaus(x, *popt), 'g', label='Fit') ## <--- plot against the contious variable
plt.xlim(xlims[0], xlims[1])
plt.ylim(0, max(data) * 1.1)
plt.savefig('normal.png')
plt.show()
预期结果是我的数据与高斯曲线拟合的直方图