FindFirstBinAbove for THStack

Hi, I quite enjoy making histograms with a fixed bin width where I set the maximum/minimum bins to very large values to avoid overflows. E.g. in PyROOT:

binwidth = 0.1
minbin,maxbin = -1000,1000
nbins = (maxbin-minbin)/binwidth
h = ROOT.TH1F("h","h",nbins,minbin,maxbin)

Then to draw the histogram properly for looking at, I use:

firstbin = h.FindFirstBinAbove(0)
lastbin = h.FindLastBinAbove(0)
h.GetXaxis().SetRange(firstbin,lastbin)

I have now a THStack with multiple histograms in it, and it is tedious to have to create a set of first/last bins and SetRange to the minimum/maximum of those sets. Would it be possible to add a FindFirstBinAbove and FindLastBinAbove method to THStack that returns the first/last bin of any of the histograms contained therein? Or is there instead a better way to properly set the axis of a THStack such that only the range of populated bins are displayed?

Thanks,
Jean-François

Try to play with this:

TH1 *h = ((TH1 *)(YourHStack->GetStack()->Last())); // the "SUM"
Int_t firstbin = h->FindFirstBinAbove(0);
Int_t lastbin = h->FindLastBinAbove(0);
TCanvas *c = new TCanvas("c", "THStack SUM");
h->Draw();

Thanks, that helps. In my own code so far I was iterating over THStack->GetHists() rather than GetStack(). Is there an important difference between these two methods of THStack? In my tests they seem to contain the same collection of histograms.

Also, is there any reason to use THStack->GetStack()->Last() over THStack->GetHists()[0]? It seems like they would all have the same axes in the end, since this is the purpose of the THStack.

Btw, my code is working now from your example, but I am wondering if there are pitfalls from using GetHists(), or using the zeroth histogram instead of the Last() one.

Jean-François

See the “fHists” and “fStack” data members of the THStack class and the THStack::BuildStack method description.
Try (compare the output, e.g. see the “number of entries” and the “total sum” of histograms):
YourHStack->GetHists()->Print();
YourHStack->GetStack()->Print();