void fwhm()
{
auto Canvas = new TCanvas();
auto h1 = new TH1F("h1", "", 50, -5.0, 5.0);
for (Int_t i = 0; i < 10000; i++) h1->Fill(gRandom->Gaus());
h1->Draw();
// method 1
auto firstBin = h1->FindFirstBinAbove(h1->GetMaximum()/2);
auto lastBin = h1->FindLastBinAbove(h1->GetMaximum()/2);
auto FWHMvalue= h1->GetBinCenter(lastBin)-h1->GetBinCenter(firstBin);
cout << "1. FWHM: " << FWHMvalue << std::endl;
// method 2 , more accurate if the distribution is Gaussian
TFitResultPtr r = h1->Fit("gaus","SQ");
auto height = r->Parameter(0);
auto mean = r->Parameter(1);
auto width = r->Parameter(2);
cout << "2. FWHM: " << 2.355*width << std::endl;
}
TGraph::GetHistogram always returns a completely “empty” histogram, which is only used to draw the axes.
In general, you would need to take the array pointers returned by TGraph::GetX and TGraph::GetY (together with the array sizes returned by TGraph::GetN) and then use some standard C++ functions to find FWHM (just make sure that you TGraph::Sort it first).
If your graph is a scatter-plot of some “well defined” known distribution, then you could use TGraph::GetRMS (and TGraph::GetMean, if needed) and “calculate” FWHM from it:
{
TGraph *g = new TGraph(10000);
for (int i = 0; i < g->GetN(); i++)
g->SetPoint(i, gRandom->Rndm(), gRandom->Gaus());
// g->Sort();
g->Draw("AP");
cout << "X Mean (exact 0.5) = " << g->GetMean(1) << endl;
cout << "X RMS (exact " << sqrt(1. / 12.) << ") = " << g->GetRMS(1) << endl;
cout << "Y Mean (exact 0.0) = " << g->GetMean(2) << endl;
cout << "Y RMS (exact 1.0) = " << g->GetRMS(2) << endl;
}