# How to fit 2-D gaussian or Lorentzian function on 2-D histogram (TH2F) and estimate the parameters (such as mean and sigma)?

ROOT Version: v6-08-06
Platform: Fedora Core 25
Compiler: GCC

Hi Dears Users and Developers:

I can plot 2-D histogram using the following commands.
How can I fit 2-D Gaussian or Lorentzian using commands and get the parameters estimated?

``````f = new TFile("opticalPhotonesCreatedByPrimary05cm.root");
TTree* t = (TTree*)f->Get("Hits");
int entries = t->GetEntries();
float posx,posy,posz;
int ncrystalcompton, ncrystalrayleigh, nphantomcompton, nphantomrayleigh;
double xmatrix(entries), ymatrix(entries), zmatrix(entries);
TH2F *xyplot = new TH2F("XY plot","Position Distribution", 1024, -204.8, 204.8, 1024, -204.8, 204.8);
for (double k = 0; k<entries; k++){
t->GetEntry(k);
xyplot->Fill(posx,posy);
}
}
``````

Thanks a lot.
Shahrokh.

To fit 2D histograms, you may have a look to fit2, fit2a or fit2dHist.

Hi,

For fiitting a 2D gaussian, which includes correlation, you can use the “bigaus” predefined function

``````TF2 * f2 = new TF2("f2","bigaus");
// set some meaningful parameters values for Constant, MeanX, .....
f2->SetParameters(Constant, MeanX, SigmaX, MeanY, SigmaY, rho );
xyplot->Fit(f2);
// retrieve fitted value ,  TF1::Print("V") to see parameter names
meanX = f2->GetParameter("MeanX");
``````

Lorenzo

Of course, I used the option of “FitPanel” with right click after drawing xyplot and I wrote the paramters given in root of my terminal. After doing it, for drawing, I set these parameters in your command.

I draw xyplot with the following commands in 3-D view:
xyplot->Draw(“lego2”);
How can I draw Gaussian function fitted with the certain parameters (the following parameters) on the result of the command mentioned above.
float Constant=2.18886e+05
float MeanX=3.83587e-03
float SigmaX=2.81282e-01
float MeanY=1.30895e-03
float SigmaY=2.82594e-01

When I select “bigaus” in “Fit Function” in the panel of “FitPanel”, I get the following result:

root [26] TFitEditor::DoFit - using function PrevFitTMP 0x9044020
FCN=136284 FROM MIGRAD STATUS=CONVERGED 266 CALLS 267 TOTAL
EDM=1.94652e-08 STRATEGY= 1 ERROR MATRIX ACCURATE
EXT PARAMETER STEP FIRST
NO. NAME VALUE ERROR SIZE DERIVATIVE
1 Constant 1.09329e+05 1.32275e+02 2.38372e+01 -1.07147e-07
2 MeanX 3.84271e-03 3.39948e-04 6.12622e-05 3.82174e-01
3 SigmaX 2.81238e-01 2.77175e-04 4.29620e-05 -5.43046e-02
4 MeanY 1.30967e-03 3.41672e-04 6.15596e-05 -3.13873e-01
5 SigmaY 2.82578e-01 2.79339e-04 4.31348e-05 -1.25725e-01
6 Rho 1.08979e-02 1.49010e-03 2.68545e-04 6.47113e-02

According to these results (in ERROR column), is this fitting good?