How to divide two 2D histograms

Dear developers,

I want to divide two 2D histograms. Can you please tell me how I divide them.

I am attaching my script.

void fakeratio_tqz()

{

   TFile *f = new TFile("May26_2.root");

   TTree *t2 = (TTree*)f->Get("demo/AnaTree");

   TH2F *h2 = new TH2F("h2","hist_vetoMu",100,0,300,100,-3,3);
   TH2F *h1 = new TH2F("h1","hist_SelMu",100,0,300,100,-3,3);
   TH2F *h3 = new TH2F("h3","hist_ratio",100,0,300,100,-3,3);

   h2->GetXaxis()->SetTitle("VetoMu_pt");
   h2->GetYaxis()->SetTitle("VetoMu_eta");
   h1->GetXaxis()->SetTitle("SelMu_pt");
   h1->GetYaxis()->SetTitle("SelMu_eta");


   t2->Draw("VetoMu_eta:VetoMu_pt >> h2","","Hist");
   t2->Draw("SelMu_eta:SelMu_pt >> h1","","Hist");

 TCanvas *c1 = new TCanvas("c1","c1",800,600) ;
 c1->Divide(2,2);
 c1->cd(1);
 h1->Draw();
 c1->cd(2);
 h2->Draw();
 
     
    /*    for (int i=0;i<=h3->GetXaxis()->GetNbins();i++)

         {
            for (int j=0;j<=h3->GetYaxis()->GetNbins();j++)

         {

     int ibin = h3->GetBin(i,j);
     double Num  = h1->GetBinContent(i,j);
     double Den    = h2->GetBinContent(i,j);

     double ratio = Num / Den ;
     h3->SetBinContent ( ibin , ratio);

}
}
*/
TH2F* ratio = h1->Divide(h2);

 c1->cd(3); 
 h3->Fill(ratio);
 h3->Draw("Hist " );

}

cheers,
Nabila

You should do:

 h1->Divide(h2);

h1 will be divided by h2. see the reference manual.

hi,

I want to divide two 2D histograms and fill its result in another 2D histogram. But when I use this command it will only draw h1.
How I can do this

TH2F *hratio = new TH2F(*h1); hratio->Divide(h2); hratio->SetNameTitle("hratio", "h1 / h2");

It is not working. It will again draw h1.
What I want to do is
h3->Draw(h1/h2);
But it is not working. Kindly see my macro above.

void fakeratio_tqz()
{
   TFile *f = new TFile("May26_2.root");

   TTree *t2 = (TTree*)f->Get("demo/AnaTree");

   TH2F *h2 = new TH2F("h2","hist_vetoMu",100,0,300,100,-3,3);
   TH2F *h1 = new TH2F("h1","hist_SelMu",100,0,300,100,-3,3);
   TH2F *h3 = new TH2F("h3","hist_ratio",100,0,300,100,-3,3);

   h2->GetXaxis()->SetTitle("VetoMu_pt");
   h2->GetYaxis()->SetTitle("VetoMu_eta");
   h1->GetXaxis()->SetTitle("SelMu_pt");
   h1->GetYaxis()->SetTitle("SelMu_eta");

   t2->Draw("VetoMu_eta:VetoMu_pt >> h2","","goff");
   t2->Draw("SelMu_eta:SelMu_pt >> h1","","goff");

   TCanvas *c1 = new TCanvas("c1","c1",800,600) ;
   c1->Divide(2,2);
   c1->cd(1);
   h1->Draw("COL");
   c1->cd(2);
   h2->Draw("COL");

   h3 = (TH2F*)h1->Clone();
   h3->GetXaxis()->SetTitle(" ");
   h3->GetYaxis()->SetTitle(" ");
   h3->SetTitle("h1/h2");
   h3->Divide(h2);
   c1->cd(3);
   h3->Draw("COL");
}

1 Like

yes it works exactly what I want.
Thank you so much

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.