# 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.

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;

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  .x aaa1.C
bin = 5
bin = 75
bin = 456
bin = 1563
bin = 2885
bin = 2890
bin = 1550
bin = 485
bin = 81
bin = 10
root 

``````

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;

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  .x aaa1.C
bin = 1550
bin = 485
bin = 81
bin = 10
root 

``````

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