Reset the bin and axis limit after merging histograms from a tree branch

If I want to reset the x axis limit of a merged histogram, I would like to get “hist->GetNbinsX()” as the last bin that has an entry > 0, but I couldn’t get the value after changing the x limits.I need a histogram whose upper edge is exactly equal to the last bin that has an entry.

void test4()
{
        int nfile=10;
        TList*list=new TList;
        for(int i=1;i<=nfile;i++){
                string fname="pp"+to_string(i)+".root";
                TFile*file=TFile::Open(fname.c_str());
                TTree*T=(TTree*)file->Get("T");
                T->Draw("multiplicity>>h","","goff");
                TH1F*h=(TH1F*)gDirectory->Get("h");
                list->Add(h);
        }
        TH1F*hist=new TH1F;
        hist->Reset();
        hist->Merge(list);
        double lastbin;
        for(int i=1;i<hist->GetNbinsX();i++){
                if(hist->GetBinContent(i) <= 0 )continue;
                lastbin=i;
        }
        cout<<lastbin<<endl;
        hist->SetAxisRange(0,lastbin);
        hist->Draw();
        cout<<hist->GetNbinsX()<<endl;

}

I don’t know the correct function that can give an answer.
Thank you…

Int_t xmin = Int_t(T->GetMinimum("multiplicity"));
Int_t xmax = Int_t(T->GetMaximum("multiplicity")) + 1;
TH1F *h = new TH1F("h", "multiplicity histogram", (xmax - xmin), xmin, xmax);
T->Project("h", "multiplicity");
TH1F *hist = (TH1F*)list->At(0)->Clone("hist");
1 Like

Thank you…

Can I do any thing with histogram to get those limits.

The solution I proposed should give all “partial” histograms with (well-aligned) non-empty outer bins only. Then the “merged” histogram should be fine, too.

You can also try TH1::FindFirstBinAbove and TH1::FindLastBinAbove to verify it.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.