Hello, I am opening a number of root files and accessing one histogram per root file. I would like to saves these histograms in a list and then later draw them all on the same histogram (after normalising). The code I have below does not work. Does anyone see the problem or can anyone suggest an alternative way to do this?
When I run this, I successfully get the png’s but I get the error below when it tried to plot them all on the same canvas when looping the list I created.
Traceback (most recent call last):
File “*.py”, line 24, in
hist_array[i].Draw()
AttributeError: ‘CPyCppyy_NoneType’ object has no attribute ‘Draw’
Yes–I also attempted adding them to a list at first–didn’t work. The THStack solved the problem. Here is an excerpt from my working code (with the exception of the file path) to give you an idea:
c_i = 0
l_i = 0
for run in runs:
path = f"/path/to/files/{run}_2023_HB3_ped.root"
print(f"Opening file: {path}")
# Select the file from which to extract histogram
file = ROOT.TFile.Open(path)
# Get the correct canvas from the file
canvas = file.Get("HB3Charge/HB3/HB3-2-Charge")
# Get the correct pad
pad = canvas.GetPad(pads[tileindex]) #26 for tile 1
# Get the histogram
hist = pad.GetPrimitive(padnames[tileindex]) #"ChargeHB3-2-3-1" for tile 1
# For some reason, color corresponding to 10 is invisible.
if c_i == 9:
c_i += 1
hist.SetLineColor(c_i+1)
# Add histograms to stack
stack.Add(hist)
legendEntry = "Run " + str(run) + ", T = " + str(temps[l_i]) + " C"
legend.AddEntry(hist, legendEntry, "f")
c_i += 1
l_i += 1
Note that in my case, the histograms I was pulling from were drawn on a pad, so I had to account for that whereas you may not.
After adding all your histograms to the stack, you will create a ROOT.TCanvas and then stack.Draw("hist"). I also did a lot of axis adjustments to ensure all the histograms would automatically fit comfortably in the viewing window.
If I plot within the loop for example, if i ==6: plot… as above. Then I do get a single histogram only for i==6 and the previous histograms are missing. Any ideas?
Maybe you are not getting the histograms correctly from the file/s, or the binnings are not the same (or your input file is damaged, or something else!). Check one by one and make sure all is as you expect.