I have 10 histograms, I add them, everything works fine. I then decide to scale the resulting histogram.
k=1/10
h.Scale(k)
h.Write()
But the histogram ends up empty. If I simply delete the line where I scale the histogram everything is fine again, except everything’s 10 times larger than it should.
Hi @Frigorifico,
uhm hard to tell what’s wrong with just this information…can you please provide a small, self-contained reproducer for your issue that we can play with/debug?
Fair! If you are using python2 you want 1./10 (note the dot) or from __future__ import division to get the python3 division behavior (/ always converts to floating point).
Hello, this is simplified version of my code that exhibits the same behaviour, you just need to feed it a file with many histograms inside
import os, sys
sys.path.append('/Users/Fer/root/build/lib')
import ROOT as root
from ROOT import TFile, TIter, TKey, gROOT
def average(directory, saveAs):
os.chdir(directory)
infile = TFile.Open(saveAs + '.root') #read root file with histograms
keyList = TIter(infile.GetListOfKeys()) #generate pointers to the histograms
key0 = TKey() #we need to sum the histograms, and so we need to get the parameters of a first histogram, but TIter ddoesn't allow indexing
for key in keyList:
key0 = key
break
h0 = key0.ReadObj() #use this to generate a blank histogram where to add all the others
keyList = TIter(infile.GetListOfKeys()) #for some reason the keys are "spent" when they are called, so we rebuild keyList
h = root.TH1F('average','Average',h0.GetNbinsX(),h0.GetXaxis().GetXmin(),h0.GetXaxis().GetXmax())
n = 0
for key in keyList: #loop through histograms adding them up
n = n+1 # to know the size of keylist since it doesn't wotk like most lists in python
cl = gROOT.GetClass(key.GetClassName()) #if something there is not a histogram, ignore it
if (not cl.InheritsFrom("TH1")):
continue
h = h + key.ReadObj() #add histograms
outfile = root.TFile('average.root', 'recreate') #create file for the final product
k=1/n
h.Scale(1/n)
h.GetYaxis().SetRangeUser(-4000,16000)
h.Write() #save it