Re: Adding histo with different specifications

From: Rene Brun (Rene.Brun@cern.ch)
Date: Fri Jan 16 1998 - 08:57:15 MET


Laurent Aphecetche wrote:

> Hi,
>
> I have 2 TH2F histograms with different specifications (e.g. y axis is
> the same, but for
> x axis, one goes from -1 to 0 and the other from 0 to 1). How can I
> merge these 2 histograms ?

The macro below can do the job. Modify it at your convenience.

Rene Brun

//--------------------macro merge.C-------------------
{
//  example of macro to merge two TH2F with different bin specs

   gROOT->Reset();
   TH2F *h1 = new TH2F("h1","h1",20,-1,0,40,-1,1);
   TH2F *h2 = new TH2F("h2","h2",20,0, 1,40,-1,1);

    //fill these histograms with gaussian distributed numbers
   Int_t i;
   Float_t x,y;
   for (Int_t i=0;i<10000;i++) {
      y = gRandom->Gaus(0,0.4);
      h1->Fill(gRandom->Gaus(-0.5,0.1),y);
      h2->Fill(gRandom->Gaus(0.5,0.1),y);
   }

   // Merge these two histograms into one
   // the following algorithm assumes that binning of h1 and h2 can
overlap
   TAxis *ax1 = h1->GetXaxis();
   TAxis *ay1 = h1->GetYaxis();
   TAxis *ax2 = h2->GetXaxis();
   TAxis *ay2 = h2->GetYaxis();
   Int_t nx1  = ax1->GetNbins();
   Int_t nx2  = ax2->GetNbins();
   Int_t ny1  = ay1->GetNbins();
   Int_t ny2  = ay2->GetNbins();
   Int_t nx   = nx1 + nx2;
   Int_t ny   = ny1 + ny2;
   Float_t xmin1 = ax1->GetXmin();
   Float_t ymin1 = ay1->GetXmin();
   Float_t xmax1 = ax1->GetXmax();
   Float_t ymax1 = ay1->GetXmax();
   Float_t xmin2 = ax2->GetXmin();
   Float_t ymin2 = ay2->GetXmin();
   Float_t xmax2 = ax2->GetXmax();
   Float_t ymax2 = ay2->GetXmax();
   Float_t xmin = TMath::Min(xmin1,xmin2);
   Float_t ymin = TMath::Min(ymin1,ymin2);
   Float_t xmax = TMath::Max(xmax1,xmax2);
   Float_t ymax = TMath::Max(ymax1,ymax2);

   TH2F *hnew = new TH2F("hnew","h1+h2",nx,xmin,xmax,ny,ymin,ymax);

   Int_t binx, biny;
   Float_t x,y;
   for (binx=1;binx<=nx1;binx++) {
      x = ax1->GetBinCenter(binx);
      for (biny=1;biny<=ny1;biny++) {
         y = ay1->GetBinCenter(biny);
         hnew->Fill(x,y,h1->GetCellContent(binx,biny));
      }
   }
   for (binx=1;binx<=nx2;binx++) {
      x = ax2->GetBinCenter(binx);
      for (biny=1;biny<=ny2;biny++) {
         y = ay2->GetBinCenter(biny);
         hnew->Fill(x,y,h2->GetCellContent(binx,biny));
      }
   }

   hnew->Draw();
}



This archive was generated by hypermail 2b29 : Tue Jan 04 2000 - 00:34:29 MET