Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
rebin.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_hist
3 /// \notebook -js
4 /// Rebin a variable bin-width histogram.
5 ///
6 /// This tutorial illustrates how to:
7 /// - create a variable bin-width histogram with a binning such
8 /// that the population per bin is about the same.
9 /// - rebin a variable bin-width histogram into another one.
10 ///
11 /// \macro_image
12 /// \macro_code
13 ///
14 /// \author Rene Brun
15 
16 #include "TH1.h"
17 #include "TCanvas.h"
18 void rebin() {
19  //create a fix bin histogram
20  TH1F *h = new TH1F("h","test rebin",100,-3,3);
21  Int_t nentries = 1000;
22  h->FillRandom("gaus",nentries);
23  Double_t xbins[1001];
24  Int_t k=0;
25  TAxis *axis = h->GetXaxis();
26  for (Int_t i=1;i<=100;i++) {
27  Int_t y = (Int_t)h->GetBinContent(i);
28  if (y <=0) continue;
29  Double_t dx = axis->GetBinWidth(i)/y;
30  Double_t xmin = axis->GetBinLowEdge(i);
31  for (Int_t j=0;j<y;j++) {
32  xbins[k] = xmin +j*dx;
33  k++;
34  }
35  }
36  xbins[k] = axis->GetXmax();
37  //create a variable bin-width histogram out of fix bin histogram
38  //new rebinned histogram should have about 10 entries per bin
39  TH1F *hnew = new TH1F("hnew","rebinned",k,xbins);
40  hnew->FillRandom("gaus",10*nentries);
41 
42  //rebin hnew keeping only 50% of the bins
43  Double_t xbins2[501];
44  Int_t kk=0;
45  for (Int_t j=0;j<k;j+=2) {
46  xbins2[kk] = xbins[j];
47  kk++;
48  }
49  xbins2[kk] = xbins[k];
50  TH1F *hnew2 = (TH1F*)hnew->Rebin(kk,"hnew2",xbins2);
51 
52  //draw the 3 histograms
53  TCanvas *c1 = new TCanvas("c1","c1",800,1000);
54  c1->Divide(1,3);
55  c1->cd(1);
56  h->Draw();
57  c1->cd(2);
58  hnew->Draw();
59  c1->cd(3);
60  hnew2->Draw();
61 }