Getting the number of bins from histogram in root

_Hello

I have a histogram and I want to get the number of bins of this his. But I cant find any thing about that in the root manual . Is there any way to do that.

Thanks in advance


Welcome to the ROOT forum.
See here.

thanks for that I use this code to get the number of bins in the hole histogram

H1F* hh2 = (TH1F*) gDirectory->Get("Pt_mu") ;
       Int_t *bins = new Int_t[hh2->GetSize()];

       for (Int_t i=0;i<hh2->GetNbinsX();i++)
 bins[i] = hh2->GetBinContent(i);
       cout<< bins;

but it does work, can anyone tell me what I miss

You do not want to get the number of bins, but the bin contents of all the bins? right?

Yes the content of all the bins

{
   auto h = new TH1F("h","h",10,-4,4);
   h->FillRandom("gaus",10000);
   h->Draw();
   float bins[10];

   int i;
   for (i=0; i<10; i++) bins[i] = h->GetBinContent(i+1);
   for (i=0; i<10; i++) printf("bin[%d] = %g\n",i,bins[i]);
}
root [0] .x aaa1.C
bin[0] = 5
bin[1] = 75
bin[2] = 456
bin[3] = 1563
bin[4] = 2885
bin[5] = 2890
bin[6] = 1550
bin[7] = 485
bin[8] = 81
bin[9] = 10
root [1] 

Thank you so much it works now.
but what if I want only the bins between the range [ 0-4] on the x-axis.

{
   auto h = new TH1F("h","h",10,-4,4);
   h->FillRandom("gaus",10000);
   h->Draw();
   float bins[10];

   int i,b=0;
   for (i=0; i<10; i++) {
      if (h->GetBinCenter(i)>=0 && h->GetBinCenter(i)<=4) {
         bins[b] = h->GetBinContent(i+1);
         b++;
      }
   }
   for (i=0; i<b; i++) printf("bin[%d] = %g\n",i,bins[i]);
}
root [0] .x aaa1.C
bin[0] = 1550
bin[1] = 485
bin[2] = 81
bin[3] = 10
root [1] 

Note that I used GetBinCenter to get the x value. You can decide for yourself what is the best way to compute x, and use a combination of GetBinLowEdge and GetBinWidth.

1 Like