Using histograms in a python script

Hi,
I am trying to fill some istograms from some variables in a tree using a python script.

This is the relevant part of my code:

{in a loop}
 histo = TH1F(sample.name,'',50,-5,500)
 histo.SetDirectory(0)
 t = f.Get('tree')
 t.Draw("chisquare>>histo")
 print '%s - %d' %(sample.name, histo.GetEntries())

where ‘chisquare’ is one of the variables in the tree (it’s a Float_t).
The problem is that when I print Entries I obtain 0.
I thought that it was beacuse the root file was not opened, but it is ok:
when the

is executed the plot is right on the Canvas, but when after the loop I try to draw the histogram the Canvas looks empty (0 entries), and I cannot draw it normalized.

Can anybody help me?

Thanks in advance,
Francesco

[quote]histo.SetDirectory(0)
t.Draw(“chisquare>>histo”)[/quote]By setting the directory of histo, you make it impossible for TTree::Draw to find it and it creates another histogram (also named ‘histo’) instead of filling your histogram.

Cheers,
Philippe.

Hi,

also, the label “histo” is a python reference thus the expression won’t know of it, and the creation of histo in a loop means that in the next iteration, it will be destroyed. Haven’t tried, and Philippe should know better than I, but I’d expect that the “histo” label in the expression would be the histogram name, and that you’d get it from gDirectory.Get(“name”).

Cheers,
Wim

Thanks for the tips, but it does not work yet.
I changed my code following what you said, now it looks like this:

  f = TFile(sample.path+sample.rootfile)
  t = f.Get('tree')

  h = TH1F(sample.name,'',50,-5,500)
  if sample.isSig: t.Draw('chisquare>>h','J1match+J2match==1')
  else: t.Draw('chisquare>>h')

  print '%s - %d' %(sample.name, h.GetEntries())

but when the ‘print’ command is reached the entries of the histogram are still 0.
[sample is weel defined, and the file are correctly opened]

Hi,

like I said: the python label has no meaning, so the “h” has no meaning in the formula expression. What might work is if you put there the known name of the histogram (i.e. the contents of sample.name):t.Draw('chisquare>>'+sample.name,'J1match+J2match==1')
Again, haven’t tried, but using python labels in the formula expression certainly isn’t going to work in any way or form.
Cheers,
Wim