Two TH2 draw problem

Hi everybody,

I don’t know if I’m doing something wrong, but when I try to draw 2 TH2D on the same canvas, the amplitude of the second one is completely wrong, see the attachment.
ROOT Version: 6.18/05 on Catalina 10.15.3

The code is this:

void testTH2(){

 gStyle->SetOptStat(0);
 
 TH2D* h1 = new TH2D("h1","h1",11,-0.5,10.5,11,-0.5,10.5);
 TH2D* h2 = new TH2D("h2","h2",11,-0.5,10.5,11,-0.5,10.5);

 for(int i=0;i<11;++i){
   h1->Fill(i*1.,i*1.,15.);
   h2->SetBinContent(i*1.,10.-1.*i,3.);

   std::cout<<"bincontent: "<<h1->GetBinContent(i,i)
        <<" "<<h2->GetBinContent(i,10-i)
        <<std::endl;
 }
 
 
 TCanvas* C1 = new TCanvas("C1","C1",800,800);
 C1->cd();
 h1->Draw("lego0");
 h2->Draw("lego0 same");  

 return;  
}

In addition, if I use Fill() also on the second TH2D the h2->GetBinContent(i,10-i) returns 0 instead of 3.
Can anyone help me? Thanks

void testTH2(){
{
   gStyle->SetOptStat(0);

   auto h1 = new TH2D("h1","h1",11,-0.5,10.5,11,-0.5,10.5);
   auto h2 = new TH2D("h2","h2",11,-0.5,10.5,11,-0.5,10.5);

   for(int i=0;i<11;++i){
      h1->Fill(i*1.,i*1.,15.);
      h2->SetBinContent(i*1.,10.-1.*i,3.);
   }

   TCanvas* C1 = new TCanvas("C1","C1",800,800);
   auto hs = new THStack();
   hs->Add(h1);
   hs->Add(h2); h2->SetFillColor(kYellow);

   hs->Draw("lego1");}
}

  for(int i = 0; i < 11; i++) {
    h1->Fill(i * 1., i * 1., 15.);
    h2->SetBinContent(i + 1, 11 - i, 3.);
    
    std::cout << "bincontent: "
              << h1->GetBinContent(i + 1, i + 1) << "  "
              << h2->GetBinContent(i + 1, 11 - i)
              << std::endl;
  }

Thanks, but actually I would like to draw both TH2 starting from 0, then use different colours and line styles to see both histograms where they superimpose. I also tried THStack with nostack or nostackb options but the result is the same as the one you posted. So my question is: is there a way to get the right bin amplitude drawing the histograms starting from 0? Thanks again.

void testTH2(){

 gStyle->SetOptStat(0);

 auto h1 = new TH2D("h1","h1",11,-0.5,10.5,11,-0.5,10.5);
 auto h2 = new TH2D("h2","h2",11,-0.5,10.5,11,-0.5,10.5);
 h1->SetLineColor(kRed);

 for(int i=0;i<11;++i){
   h1->Fill(i*1.,i*1.,15.);
   h2->SetBinContent(i*1.,10.-1.*i,3.);
 }

 double max = TMath::Max(h1->GetMaximum(), h2->GetMaximum());
 h1->SetMaximum(max);
 h2->SetMaximum(max);
 TCanvas* C1 = new TCanvas("C1","C1",800,800);
 h1->Draw("lego0");
 h2->Draw("lego0 same");
}

1 Like

Thanks, it worked. Thanks also to Wile_E_Coyote, that was an error due to the fact that I was changing from Fill() to SetBinContent() back and forth.

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