Superimposing histograms in PyROOT

Hi all,

I met a technical problem in putting several histograms together and combining them. What happens when running my code is that the previous histogram always disappear when a new histogram is drawn. This is because of the scope of the Python language. Thank Danilo Piparo for providing the correct code. The problem is solved. I’m posting this problem and solution here so that people who meet similar problem in the future can reference it.

------------------------original code (not working)--------------------------

from ROOT import *
from glob import glob

gROOT.Reset()
gStyle.SetOptStat(0)

inputDir="NtupleToHist/hist_generated/*.root"

c1 = TCanvas( 'c1', 'Example'',700, 500 )

val = 0

for filename in glob(inputDir):
    print filename
    f1=TFile(filename, 'R')
    hist=f1.Get("hist_1Lep_ttbar_2tag3jet_75_150ptv_WhfSR_BDT_Nominal")
    hist.SetName("hist_1Lep_ttbar_2tag3jet_75_150ptv_WhfSR_BDT_Nominal")
    hist.Rebin(20)
    val = val + 1
    hist.SetLineColor(val)
    hist.Scale(1/hist.Integral())
    hist.Draw("same")
    c1.Update()
c1.SaveAs("example.eps")

Best,
Peilong

Hi Peilong,

the problem here is the fact that the histograms go out of scope after each loop step. You can draw the copy of those.
I took the freedom to also draw with the same option the histograms drawn after the first one:

from ROOT import *
from glob import glob

gStyle.SetOptStat(0)

inputDir="NtupleToHist/hist_generated/*.root"

c1 = TCanvas( 'c1', 'Example',700, 500)

val = 0
print glob(inputDir)

for i,filename in enumerate(glob(inputDir)):
    print filename
    f1=TFile(filename, 'R')
    hist=f1.Get("hist_1Lep_ttbar_2tag3jet_75_150ptv_WhfSR_BDT_Nominal")
    hist.SetName("hist_1Lep_ttbar_2tag3jet_75_150ptv_WhfSR_BDT_Nominal")
    hist.Rebin(20)
    val = val + 1
    hist.SetLineColor(val)
    hist.Scale(1/hist.Integral())
    option = "" if i == 0 else "same"
    hist.DrawCopy(option)
    c1.Update()
raw_input("Press enter to save the image")
c1.SaveAs("example.eps")

Cheers,
D

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.