THStack::GetHistogram() null pointer error

Hi,

I was trying to set a title to the X axis of a THStack containing several plots.

Looking at the forum I found that I should use the GetHistogram() function like:

thstack.GetHistogram().GetXaxis().SetTitle("title")

But when I have more than one histo in the stack, GetHistogram() returns me a null pointer.
Maybe am I missing something?

Here an example:

>>> h1 = ROOT.TH1F("h1", "ciao bello", 100, 0., 100.)
>>> h2 = ROOT.TH1F("h2", "ciao bello!!!", 100, 0., 100.)
>>> ths = ROOT.THStack("ths", "pippo")
>>> ths.Add(h1)
>>> ths.GetHistogram()
<ROOT.TH1F object ("ths") at 0xa91400>
>>> ths.Add(h2)
>>> ths.GetHistogram()
<ROOT.TH1 object at 0x0>    -------> NULL pointer!!!
>>> ths.GetHistogram().GetXaxis()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ReferenceError: attempt to access a null-pointer
>>> 

Thanks a lot for your kind help,

Ric.

I made some further tests and apparently drawing the THStack somehow “activate” it:

>>> import ROOT
>>> h1 = ROOT.TH1F("h1", "ciao bello", 100, 0., 100.)
>>> h2 = ROOT.TH1F("h2", "ciao bello!!!", 100, 0., 100.)
>>> ths = ROOT.THStack("ths", "pippo")
>>> ths.Add(h1)
>>> ths.GetHistogram()
<ROOT.TH1 object at 0x0>                      -----> NULL POINTER!!!
>>> ths.Draw()                                        ----->  DRAWING THE THSTACK!!!
<TCanvas::MakeDefCanvas>: created default TCanvas with name c1
>>> ths.GetHistogram()
<ROOT.TH1F object ("ths") at 0xa4f200>   ------> NOW IT'S NOT NULL POINTER ANYMORE
>>> ths.Add(h2)
>>> ths.GetHistogram()
<ROOT.TH1 object at 0x0>
>>> ths.Draw()
<TCanvas::MakeDefCanvas>: created default TCanvas with name c1
>>> ths.GetHistogram()
<ROOT.TH1F object ("ths") at 0x4818000>
>>> 

So if I draw the thstack before trying to use GetHistogram() on it, everything works.

But drawing a THStack is not always possible, especially when creating hundreds of THStacks in a script: in this scenario it would be better to create them, access the histo and its axis to set the title without having to draw it, and save directly the newly created thstack in an output .root file.

Is there any way to “activate” the THStack without drawing it?

Many thanks again,

Ric.

Yes that’s how it is working.

1 Like

Hi,

and is there any way to “activate” the thstack without drawing it, to be used for example in a loop inside a script?

Thanks,

Ric.

I do not know what you mean by “activate”… a THStack is only a list of histograms. The histogram returned by the GetHistogram function is a temporary one used only for drawing purpose (axis drawing mainly). So it exist only when the THStack is drawn.

Ok, I see. The THStack loads the histos into the memory only when it’s drawn.

Thanks for the clarification,

Ric.

No … the histograms are in memory … They are group in a list: a THStack object.
The temporary histogram returned by THStack::GetHistogram() is created only at drawing time.