User Tools

Site Tools


root:pyroot_tfile

This is an old revision of the document!


Handling TH1 histograms

Filling a histogram

Simple enough:

hist = TH1D("hist_name","hist title",100,0,100)
for i in xrange(10000):
    hist.Fill(gRandom.Gauss())

With some weight:

weight = gRandom.Gauss(1,0.1)
hist.Fill(gRandom.Gauss(),weight)

Filling a histogram from a tree

The classic way would be

hist = TH1D("hist_name","hist title",100,0,100)
for event in tree:
    hist.Fill(tree.px)

But the simplest and most powerful way to draw some variable into a histogram, is with the Draw function:

hist = TH1D("hist_name","hist title",100,0,100)
tree.Draw("px >> hist_name")

Note that the histogram has been saved into ROOT's working memory and is therefore accessible via its name in the Draw function, “hist_name” in this example.

You can also use mathematical expressions:

tree.Draw("2*sqrt(px*px+py*py) >> hist_name")
tree.Draw("abs(eta) >> hist_name")

You can apply some selections using variable, available in the tree's branches:

tree.Draw("px >> hist_name","pt>20 && E>20")

You can apply some selections and/or a weight, if a weight variable is available in the tree:

tree.Draw("px >> hist_name","(pt>20 && E>20)*weight")
tree.Draw("px >> hist_name","weight")

An equivalent method is creating the histogram in the Draw method. If you need the TH1F object, you can still get it with gDirectory (see below):

from ROOT import gDirectory
...
tree.Draw("pt >> h(100,0,100)")
hist = gDirectory.Get("h") # will be a TH1F object

It's also possible to pass some option you would normally use in “TH1::Draw()”. It is passed as the third string.

tree.Draw("px >> h1(100,0,100)","","E2")
tree.Draw("py >> h2(100,0,100)","","E2 SAME")
 
tree.Draw("px >> h1(100,0,100)","abs(eta)>2","E2")
tree.Draw("px >> h2(100,0,100)","abs(eta)<2","E2 SAME")

Protip: This is very useful for quick drawing and comparing, for example in the ROOT command line.

$ root -l tree.root
[1] tree->Draw("px >> h1(100,0,100)","","E2")
[2] tree->Draw("py >> h2(100,0,100)","","E2 SAME")
root/pyroot_tfile.1497339438.txt.gz · Last modified: 2017/06/13 09:37 by iwn