Hi, I was trying to plot a histogram from 5 text files having two columns each. The first column is time in order of nanoseconds and second column is number of events. I want an overlay plot of 5 different histograms. I have used the following code.
import os, sys
import ROOT
from array import *
# Define the file names and their corresponding colors
file_names = ["test1.txt", "test2.txt", "test3.txt", "test4.txt", "test5.txt"]
colors = [1, 2, 3, 4, 6]
# Create an empty list to hold the histograms
hist_list = []
# Loop over the file names and create a histogram for each file
for i, fname in enumerate(file_names):
f = open(fname)
lines = f.readlines()
xValues = []
yValues = []
for l in lines:
if "Time" in l or "LECROY" in l or "Segment" in l or "#" in l or "," not in l:
continue
xVal = l.split(" ")[0]
yVal = l.split(" ")[1].split("\n")[0]
xValues.append(float(xVal))
yValues.append(float(yVal))
binWidth = xValues[1] - xValues[0]
histo = ROOT.TH1F(fname, fname, len(xValues), xValues[0]-binWidth/2, xValues[-1]+binWidth/2)
for y in yValues:
histo.Fill(y)
histo.SetLineColor(colors[i])
histo.SetLineWidth(2)
hist_list.append(histo)
# Draw the histograms on a canvas
can = ROOT.TCanvas("can", "can", 800, 600)
can.cd()
legend = ROOT.TLegend(0.7, 0.7, 0.9, 0.9)
for i, histo in enumerate(hist_list):
if i == 0:
histo.Draw()
else:
histo.Draw("SAME")
legend.AddEntry(histo, file_names[i], "l")
legend.Draw()
can.Update()
can.Print("test.pdf")
sys.exit()
This gives the following error-
File "hist_txt2.py", line 25, in <module>
binWidth = xValues[1] - xValues[0]
IndexError: list index out of range
Also, the files have different x values from each other. So I want to take the whole range or define it manually. Thanks.