Skip to content

Instantly share code, notes, and snippets.

@mastbaum
Created June 20, 2014 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mastbaum/7d4831fa935af903b5ed to your computer and use it in GitHub Desktop.
Save mastbaum/7d4831fa935af903b5ed to your computer and use it in GitHub Desktop.
Example of drawing overlaid histograms from two TTrees in two TFiles
// Draw overlaid histograms from a RAT ntuple (for example).
//
// Usage:
// $ root -l -x 'overlay.C("filename1.root", "filename2.root")'
//
// The trick is that histograms are associated with a TDirectory
// upon creation, which is most likely the open file. When the
// directory changes when a new file is opened, the pointer to
// the histogram is invalidated. TH1::SetDirectory is used to
// detach a histogram from a file.
void overlay(TString file1, TString file2) {
TFile f1(file1);
TTree* t1 = (TTree*) f1.Get("output");
TH1F* h1 = new TH1F("h1", "nhits", 100, 0, 2000);
t1->Draw("nhits>>h1", "", "goff");
h1->SetDirectory(0); // Trick: detach histogram from the file!
f1.Close();
TFile f2(file2);
TTree* t2 = (TTree*) f2.Get("output");
TH1F* h2 = new TH1F("h2", "nhits", 100, 0, 2000);
t2->Draw("nhits>>h2", "", "goff");
h2->SetDirectory(0);
f2.Close();
TCanvas* c = new TCanvas();
h1->Scale(1.0 / h1->Integral());
h1->Draw();
h2->Scale(1.0 / h2->Integral());
h2->SetLineColor(kRed);
h2->Draw("same");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment