Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fitting a histogram with python

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?

like image 981
Brian Avatar asked Oct 18 '11 10:10

Brian


People also ask

How do you fit a histogram?

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.


1 Answers

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() 

enter image description here

like image 199
joaquin Avatar answered Oct 05 '22 23:10

joaquin