User Tools

Site Tools


root:ttreedraw

TTree::Draw()

Basic Usage

The Draw()-Method of TTrees is a very useful tool to quickly create histograms. The following code creates a histogram with the default settings.

TFile file("myfile.root");
TTree *tree = file.Get("mytree");
tree->Draw("myvar");

Alternatively the name of the histogram to be created can be given or the data can be added to an existing histogram.

tree->Draw("myvar>>myhist(10,0,100)");     // create a new histogram *myhist* with 10 bins between 0 and 100
TH1F *hist = gPad->GetPrimitive("myhist"); // create a pointer to the new histogram
tree->Draw("myvar>>+myhist");              // add additional entries to *myhist*

For more information have a look at the official TTree::Draw documentation.

Useful Tricks

Using a Custom Function in TTree::Draw

You can define a custom function and use it in the expression of TTree::Draw.

To apply such a function it must be known to CINT. This can be done with ProcessLineSync

This example expects that there is a TTree object named tree containing a TBranch called x.

test.py
import ROOT
ROOT.gROOT.ProcessLineSync(".x test.C+")
print ROOT.test(1) # prints 3.0 (this line works only in pyROOT and CINT, not in compiled code)
tree.Draw("x:test(x)")

It loads the following example function:

test.C
double test(double in = 0)
{
  return in*3;
}

Please note that the function is named “test” as the file name without the “.C” and has default arguments for all variables. If one of those is missing you get an error (even though it may still work).

Data structures (like histograms) can be stored in a global pointer known to cint. These can be defined and initialised in another call of ProcessLineSync.

h = ROOT.TH1D("myHist","",0,1,10)
ROOT.gROOT.ProcessLineSync("TH1D * myHist = (TH1D*) gDirectory.Get("myHist")")

To be used in test.C they have to be defined there as well:

test.C
TH1D * myHist = 0;
double test(double in = 0)
{
  if (!myHist)
     return 0;
  return myHist->GetBinContent(myHist->FindBin(in));
}

Pitfalls

Unable to add to existing histograms

Adding data to an existing histogram will fail, if any file was opened after creating the histogram! TTree::Draw() searches for the named histogram in the active directory - and this is changed when opening a file.

To avoid this make sure to load the input files before you create any histograms or create a storage file and switch back there after opening any files:

TFile tmp("tmp.root", "recreate");
float bins[] = {0, 10, 20, 40, 80}; 
TH1F  myhist("myhist", "myhist", 4, bins)
 
TFile file("myinput.root");
TTree *tree = file.Get("mytree");
 
tmp.cd()
tree->Draw("myvar>>+myhist");
root/ttreedraw.txt · Last modified: 2013/06/14 11:41 by nchiap