Automatic rebin for THStack

Dear all,

Let be a THStack containing two histos. These histos have the kCanRebin bit set because I don’t know what will be the maximum value of either of the histos. Unfortunately, the span of the axis correspond only to the “main” histo, it doesn’t take into account the second one. Here is an example:

TH1F * h1 = new TH1F("h1", "h1", 1000, 0, 1) ; TH1F * h2 = new TH1F("h2", "h2", 1000, 0, 1) ; h1->SetBit(TH1::kCanRebin) h2->SetBit(TH1::kCanRebin) h1->SetLineColor(kBlue) h2->SetLineColor(kRed) THStack stack; stack.Add(h1) stack.Add(h2) stack.SetHistogram(h1) stack.Draw("nostack") h1->Fill(2) h2->Fill(5) gPad->Modified()
At the end of this script, the value 5 of h2 is not visible.

Is there a way to have the axis of the stack to adapt to the maximum value of any of its histo ?

Thanks in advance,

Why do you call stack.SetHistogram ? simply do:

{ TH1F * h1 = new TH1F("h1", "h1", 1000, 0, 1) ; TH1F * h2 = new TH1F("h2", "h2", 1000, 0, 1) ; h1->SetBit(TH1::kCanRebin); h2->SetBit(TH1::kCanRebin); h1->SetLineColor(kBlue); h2->SetLineColor(kRed); THStack stack; stack.Add(h1); stack.Add(h2); stack.Draw("nostack"); h1->Fill(2); h2->Fill(5); gPad->Modified(); }


Hello René,

If I remove the SetHistogram, then the axis remain at 0…1 and no data is shown.

I use ROOT 5.26.00b.


Hi again,

I have found the following way of achieving what I wanted. I have a subclass of THStack called MultiColorH1F. I loop on its histograms to find the one with the maximum x axis and do a SetHistogram with this histo. I do it at regular interval and it works as long as all the histo have the same minimum x value.

Here is the methods that implement it:

// fHistos contains the histograms of the THStack

float MultiColorH1F::GetMaxXAxis(int index)
// Return the maximum value on the x axis for histogram at index

TAxis *axis = fHistos[index]->GetXaxis();
return axis->GetBinCenter(axis->GetLast());

int MultiColorH1F::GetHistoIndexWithMaxXAxis()
// Returns the index of the histogram with the maximum X axis

int currentMax = 0;
float result = FLT_MIN;
for(unsigned int i = 0 ; i < fHistos.size() ; i++) {
float max = GetMaxXAxis(i);
if(max > result) {
result = max;
currentMax = i;
return currentMax;

void MultiColorH1F::UpdateRangeXAxis()
// Make sure we use the axis of the plot with the maximum x axis

if(fHistos.size() <= 0) {

int currentMax = GetHistoIndexWithMaxXAxis();

It is not ideal. If there is a better way of doing this, I would be grateful to know about it.

Best regards,