Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
fit1.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_fit
3 /// \notebook
4 /// Simple fitting example (1-d histogram with an interpreted function)
5 ///
6 /// \macro_image
7 /// \macro_output
8 /// \macro_code
9 ///
10 /// \author Rene Brun
11 
12 #include "TCanvas.h"
13 #include "TFrame.h"
14 #include "TBenchmark.h"
15 #include "TString.h"
16 #include "TF1.h"
17 #include "TH1.h"
18 #include "TFile.h"
19 #include "TROOT.h"
20 #include "TError.h"
21 #include "TInterpreter.h"
22 #include "TSystem.h"
23 #include "TPaveText.h"
24 
25 void fit1() {
26  TCanvas *c1 = new TCanvas("c1_fit1","The Fit Canvas",200,10,700,500);
27  c1->SetGridx();
28  c1->SetGridy();
29  c1->GetFrame()->SetFillColor(21);
30  c1->GetFrame()->SetBorderMode(-1);
31  c1->GetFrame()->SetBorderSize(5);
32 
33  gBenchmark->Start("fit1");
34  //
35  // We connect the ROOT file generated in a previous tutorial
36  // (see <a href="fillrandom.C.nbconvert.ipynb">Filling histograms with random numbers from a function</a>)
37  //
38  TString dir = gROOT->GetTutorialDir();
39  dir.Append("/fit/");
40  TFile *file = TFile::Open("fillrandom.root");
41  if (!file) {
42  gROOT->ProcessLine(Form(".x %s../hist/fillrandom.C",dir.Data()));
43  file = TFile::Open("fillrandom.root");
44  if (!file) return;
45  }
46 
47  //
48  // The function "ls()" lists the directory contents of this file
49  //
50  file->ls();
51 
52  //
53  // Get object "sqroot" from the file. Undefined objects are searched
54  // for using gROOT->FindObject("xxx"), e.g.:
55  // TF1 *sqroot = (TF1*) gROOT.FindObject("sqroot")
56  //
57  TF1 * sqroot = 0;
58  file->GetObject("sqroot",sqroot);
59  if (!sqroot){
60  Error("fit1.C","Cannot find object sqroot of type TF1\n");
61  return;
62  }
63  sqroot->Print();
64 
65  //
66  // Now get and fit histogram h1f with the function sqroot
67  //
68  TH1F* h1f = 0;
69  file->GetObject("h1f",h1f);
70  if (!h1f){
71  Error("fit1.C","Cannot find object h1f of type TH1F\n");
72  return;
73  }
74  h1f->SetFillColor(45);
75  h1f->Fit("sqroot");
76 
77  // We now annotate the picture by creating a PaveText object
78  // and displaying the list of commands in this macro
79  //
80  TPaveText * fitlabel = new TPaveText(0.6,0.4,0.9,0.75,"NDC");
81  fitlabel->SetTextAlign(12);
82  fitlabel->SetFillColor(42);
83  fitlabel->ReadFile(Form("%sfit1_C.txt",dir.Data()));
84  fitlabel->Draw();
85  c1->Update();
86  gBenchmark->Show("fit1");
87 }