#!/usr/bin/env python # coding: utf-8 # # Fitting #
# This ROOTbook shows how to create a [histogram](https://root.cern.ch/doc/master/classTH1F.html), [fill it](https://root.cern.ch/doc/master/classTH1.html#a77e71290a82517d317ea8d05e96b6c4a) and [fit it](https://root.cern.ch/doc/master/classTH1.html#a7e7d34c91d5ebab4fc9bba3ca47dabdd). # # Let's start importing the [ROOT](https://root.cern.ch) module, which gives us access to all [ROOT](https://root.cern.ch) classes, and activate the [JSROOT](https://root.cern.ch/js/) visualisation. # In[1]: import ROOT # In[2]: get_ipython().run_line_magic('jsroot', 'on') # Now we will create a [histogram](https://root.cern.ch/doc/master/classTH1F.html) 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](https://root.cern.ch/doc/master/classTF1.html) 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. # 1. Create a new, fresh canvas and draw the histogram in it. # 2. Find back the canvas which was created (see the message above!) and draw it. # The fitted function is now associated of the histogram: no special operation is needed. # # 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.