In [1]:
import ROOT
In [2]:
%jsroot on
Now we will create a histogram specifying its title and axes titles. We'll also subsequently fill it with gaussian random numbers.
In [3]:
h = ROOT.TH1F("myHisto","My Histo;X axis;Y axis",64, -4, 4)
h.FillRandom("gaus")
We now setup our fit. ROOT provides a set of predefined functions, among which the Gaussian. You can have a look to the TF1 class documentation to learn more about how functions are implemented in ROOT. For example you will see that you can define functional forms with strings, lambda functions or other kind of functors.
We specify the option "S" to extract the information relative to the fit in a separate object: we will inspect it later.
In [4]:
fitResultPtr = h.Fit("gaus","S")
You can see above the output of the fit, which converged. The value, uncertainty and other useful quantities are reported for each parameter.
If more detail is needed, other information can be extracted, for example the final chi-square value or the number of free parameters:
In [9]:
chi2_nparams = (fitResultPtr.Chi2(), fitResultPtr.NFreeParameters())
print "The final Chi2 value was %.2f and the number of free parameters was %d" %chi2_nparams
So far so good. Now we can draw our fitted histogram. We have two options.
Let's tackle this task following option 2. ROOT keeps track of all canvases and it is trivial to retrieve any of them by name.
In [13]:
c1 = ROOT.gROOT.GetListOfCanvases().FindObject("c1")
c1.Draw()
Congratulations! You accomplished your fit.