Sometimes you need to fit a function to a histogram in ROOT. Attached is code for how to do that in the simple case of a power law fit.
To run the example, you should type "root fitSnr.C" in the command line. The code will access the source histogram (hstrip1nsr.root, which is actually ANITA-2 satellite data). The result is stripe1snrfit.png. |
#include "TF1.h"
void fitSnr();
void fitSnr()
{
gStyle->SetLineWidth(4); //set some style parameters
TFile *stripe1file = new TFile("hstripe1snr.root"); //import the file containing the histogram to be fit
TH1D *hstripe1 = (TH1D*)stripe1file->Get("stripe1snr"); //get the histogram to be fit
TCanvas c1("c1","c1",1000,800); //make a canvas
hstripe1->Draw(""); //draw it
c1.SetLogy(); //set a log axis
//need to declare an equation
//I want to fit for two paramters, in the equation these are [0] and [1]
//so, you'll need to re-write the equation to whatever you're trying to fit for
//but ROOT wants the variables to find to be given as [0], [1], [2], etc.
char equation1[150]; //declare a container for the equation
sprintf(equation1,"([0]*(x^[1]))"); //declare the equation
TF1 *fit1 = new TF1("PowerFit",equation1,20,50); //create a function to fit with, with the range being 20 to 50
//now, we need to set the initial parameters of the fit
//fit->SetParameter(0,H->GetRMS()); //this should be a good starting place for a standard deviation like variable
//fit->SetParameter(1,H->GetMaximum()); //this should be a good starting place for amplitude like variable
fit1->SetParameter(0,60000.); //for our example, we will manually choose this
fit1->SetParameter(1,-3.);
hstripe1->Fit("PowerFit","R"); //actually do the fit;
fit1->Draw("same"); //draw the fit
//now, we want to print out some parameters to see how good the fit was
cout << "par0 " << fit1->GetParameter(0) << " par1 " << fit1->GetParameter(1) << endl;
cout<<"chisquare "<<fit1->GetChisquare()<<endl;
cout<<"Ndf "<<fit1->GetNDF()<<endl;
cout<<"reduced chisquare "<<double(fit1->GetChisquare())/double(fit1->GetNDF())<<endl;
cout<<" "<<endl;
c1.SaveAs("stripe1snrfit.png");
}
|