Curve fitting only part of data/histogramm (python, matplotlib)

Viewed 409

Say I got a histogramm which resembles a normal distribution but is slightly asymmetric.

Say I want to fit only the peak of my distribution witt a gaussian, i.e. only the data in a small range around the peak should be taken into account. How do I do that? Here my code so far:

def gaussian(x,  mean, amplitude, standard_deviation):
    return amplitude * np.exp( - ((x - mean) / standard_deviation) ** 2)
    

#Histogram
fig, ax = plt.subplots()
y, x, _ = ax.hist(data, bins = 'auto')

#Fit
bin_centers = x[:-1] + np.diff(x) / 2
params, cov = sp.optimize.curve_fit(gaussian, bin_centers, y, p0=[x.max(), 100, 5000])
x_values = np.linspace(0, 70000, 1000)
plt.plot(x_values, gaussian(x_values, *params), label='fit')
1 Answers

Print the hist and bin_centers. Then only fit the part you need. I had a similar code where I fitted using a normal fit.

    hist, bin_edges = np.histogram(data, bins='auto') #get hist and bin_edges
bin_centers = .5*(bin_edges[:-1] + bin_edges[1:]) #get bin_centers
A = bin_centers[m:n] #values of bin_centers of only the part you need, in my case it was index m to index n.
B = hist[m:n] #values of histogram of only the part you need
slope, c = np.polyfit(A, B, 1) #fit curve (y) = m*(x) + c
deg_fit = (slope*A + c) #calculate the fitted values of y
plt.plot(bin_centers[m:n],deg_fit)
Related