I have a histogram
H=hist(my_data,bins=my_bin,histtype='step',color='r')
I can see that the shape is almost gaussian but I would like to fit this histogram with a gaussian function and print the value of the mean and sigma I get. Can you help me?
To fit a histogram with a predefined function, simply pass the name of the function in the first parameter of TH1::Fit . For example, this line fits histogram object hist with a Gaussian.
Here you have an example working on py2.6 and py3.2:
from scipy.stats import norm import matplotlib.mlab as mlab import matplotlib.pyplot as plt # read data from a text file. One number per line arch = "test/Log(2)_ACRatio.txt" datos = [] for item in open(arch,'r'): item = item.strip() if item != '': try: datos.append(float(item)) except ValueError: pass # best fit of data (mu, sigma) = norm.fit(datos) # the histogram of the data n, bins, patches = plt.hist(datos, 60, normed=1, facecolor='green', alpha=0.75) # add a 'best fit' line y = mlab.normpdf( bins, mu, sigma) l = plt.plot(bins, y, 'r--', linewidth=2) #plot plt.xlabel('Smarts') plt.ylabel('Probability') plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=%.3f,\ \sigma=%.3f$' %(mu, sigma)) plt.grid(True) plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With