Converting TH1F into a TGraph with smooth line connecting all the points

Dear All,

I have plotted a TH1F histogram, I would like to now plot a TGraph from this histogram. But don’t know how to go about doing that, may I have some kindly.

Int_t n =  6000000;
Float_t norm = sigma/h_rapidity->Integral("width");// normalizing histogram to cross-section
 // hdndy->Scale(sigma/(binwidth *nevents)); 
hdndy = (TH1F*)h_rapidity->Clone();// making copy of rapidity histogram
hdndy->GetXaxis()->SetTitle(" Rapidity");
hdndy->GetYaxis()->SetTitle("d\sigma/dy");
hdndy->Scale(norm); //d\sigma/dy histogram.
hdndy->Draw("CL");

Thank you.

Plotting the histogram with option L should draw the histogram as a line. But you may need in addition the option HIST if your histogram has errors:

hdndy->Draw("HIST L");

Perhaps even the option "C" might be more appealing with a splined curve between the bins. More information on the 1D histogram plotting options: https://root.cern.ch/doc/master/classTHistPainter.html#HP01b

Thank you

I am still not able to transform this TH1F into a TGraph, I added this portion to the above code but TGraph is blank.

Int_t j = 100;// number of bins

Double_t x[60000];
Double_t y[60000];
for(int i = 0; i GetNbinsX; i++ )
{
x[i] = hdndy->GetBinCenter(i) ;
y[i] = hdndy->GetBinContent(i);
}

cout << x[i] << y[i] << endl;
TGraph *gr = new TGraph(j, x,y);
TCanvas *a = new TCanvas(“Rapidity”," ",600,600);
gr->Draw();

void h2g() {
   auto h = new TH1F("h","h",100,-4,4);
   h->FillRandom("gaus",20000);
   auto g = new TGraph();
   for(int i = 1; i <= h->GetNbinsX(); i++ ) g->SetPoint(i-1, h->GetBinCenter(i), h->GetBinContent(i));
   g->Draw("AL");
}
1 Like