Get bin label from bin number

ROOT Version: 6.26/04
Platform: macOS Monterey 12.4
Compiler: Not Provided


I have a set of TH1 histograms with TStrings for bin labels, and I’m trying to get the labels from the bins after they’ve been sorted and filtered as I need. I can get a THashList setup by:

THashList hash = hist->GetXaxis()->GetLabels();

but I’m unsure how to access and store the individual elements of that Hash List. Ideally I’d like to access it by bin number. There is more code below for some further context

hist->LabelsDeflate();
hist->GetXaxis()->LabelsOption(">");
hist->GetXaxis()->SetRangeUser(0,9); // Only want top 10 contributing reactions
hist->Scale(100./hist->Integral()); // Normalize top 10 bins
for(Int_t bin=1; bin<10; bin++) {
    if(hist->GetBinContent(bin) > 0.1) {
        THashList hash = hist->GetXaxis()->GetLabels();
        // Find bin label and store into an array
    } 
}

For reference doing the command below outputs something like:

hist->GetXaxis()->GetLabels()->Print();

// Output
Collection name='THashList', class='THashList', size=205
 TObjString = 3#gamma#pi^{#plus}#pi^{#minus}p[#pi^{0},#omega]
 // Hundreds more strings here

Try with:

for(Int_t bin=1; bin<10; bin++) {
    if(hist->GetBinContent(bin) > 0.1) {
        cout << hist->GetXaxis()->GetLabels()->At(bin-1)->GetName() << endl;
    } 
}

Note that for TList::At(), you start with zero, while bin numbers start from 1, hence the bin-1. Read also about TObject::GetName()

{
  const Int_t nx = 20;
  const char *people[nx] = {"Jean","Pierre","Marie","Odile","Sebastien",
     "Fons","Rene","Nicolas","Xavier","Greg","Bjarne","Anton","Otto",
     "Eddy","Peter","Pasha","Philippe","Suzanne","Jeff","Valery"};
  TCanvas *c1 = new TCanvas("c1","demo bin labels",10,10,900,500);
  c1->SetGrid();
  c1->SetTopMargin(0.15);
  TH1F *h = new TH1F("h","test",3,0,3);
  h->SetStats(0);
  h->SetFillColor(38);
  h->SetCanExtend(TH1::kAllAxes);
  for (Int_t i=0;i<5000;i++) {
     Int_t r = gRandom->Rndm()*20;
     h->Fill(people[r],1);
  }
  h->LabelsDeflate();
  h->Draw();
  TPaveText *pt = new TPaveText(0.7,0.85,0.98,0.98,"brNDC");
  pt->SetFillColor(18);
  pt->SetTextAlign(12);
  pt->AddText("Use the axis Context Menu LabelsOption");
  pt->AddText(" \"a\"   to sort by alphabetic order");
  pt->AddText(" \">\"   to sort by decreasing values");
  pt->AddText(" \"<\"   to sort by increasing values");
  pt->Draw();
  for (int i=0; i<nx; ++i) {
    cout <<h->GetXaxis()->GetLabels()->At(i)->GetName()<<endl;
  }
}


root[] .x aa.C
Jeff
Peter
Sebastien
Fons
Anton
Suzanne
Philippe
Valery
Pasha
Greg
Bjarne
Odile
Nicolas
Rene
Otto
Marie
Eddy
Pierre
Xavier
Jean

2 Likes