Automatically find maximum of several histogramms in TCanvas

Dear Rooters,

a problem I stumble across ever so often:

Drawing multiple histogramms into a Canvas, the first histogram will define the axis range in both x & y.

Is there an elegant way – I know how to do it non-elegantly – to set the maximum(minimum) of the y-axis to the highest maximum from all histograms, such that all histograms are completely visible at the same time without further need for readjusting scales?

Best regards,

Erik

Use a THStack. See: $ROOTSYS/tutorials/hist/hstack.C

1 Like

Somehow I am getting in trouble since I want to read histograms from files from a TChain and adding them to the stack as shown below, the code always produces a seg fault

TChain *chain = new TChain();
chain->Add("somefilename*.root");
TObjArray *fileElements=chain->GetListOfFiles();
TIter next(fileElements);
TChainElement *chEl=0;
THStack *stack = new THStack("name","title");
 while (( chEl=(TChainElement*)next() )) {
    TFile f(chEl->GetTitle());
    TKey* k_gain = f.FindKeyAny("histoname");
    TH1* h_gain = static_cast<TH1*>(k_gain->ReadObj());
    stack->Add(h_gain);

}

stack->Draw("nostack");

It seems to me that the objects disappear when the file is closed, even when introduce another Clone statement.
The problem did not arise when I just used the histograms since I made a DrawCopy() . Probably something stupid I am overlooking.

Any hint is appreciated.

Erik

Add the line marked with <====== to your code

TChain *chain = new TChain();
chain->Add("somefilename*.root");
TObjArray *fileElements=chain->GetListOfFiles();
TIter next(fileElements);
TChainElement *chEl=0;
THStack *stack = new THStack("name","title");
 while (( chEl=(TChainElement*)next() )) {
    TFile f(chEl->GetTitle());
    TKey* k_gain = f.FindKeyAny("histoname");
    TH1* h_gain = static_cast<TH1*>(k_gain->ReadObj());
     h_gain->SetDirectory(0); //<================
    stack->Add(h_gain);

}

stack->Draw("nostack");

Rene

Hi Rene,

the line you indicate indeed solved the problem, thanks.

Somehow I keep forgetting about the directory association of the histograms.

Best regards

Erik

How do I resolve the same problem if I draw a THStack, a TGraph and a TH1 on the same canvas?

https://root.cern/doc/master/classTHStack.html#a76deae09231652a9e1c3e65fb5cdc3c5

@couet, it would be nice if the canvas was intelligent and would automatically adjust its own maximum depending on what gets drawn on it.

It is exactly what it does when you Draw a THStack.