Plot an overlay histogram from multiple .txt files

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:
        xVal = l.split(" ")[0]
        yVal = l.split(" ")[1].split("\n")[0]
    binWidth = xValues[1] - xValues[0]
    histo = ROOT.TH1F(fname, fname, len(xValues), xValues[0]-binWidth/2, xValues[-1]+binWidth/2)
    for y in yValues:

# Draw the histograms on a canvas
can = ROOT.TCanvas("can", "can", 800, 600)
legend = ROOT.TLegend(0.7, 0.7, 0.9, 0.9)
for i, histo in enumerate(hist_list):
    if i == 0:
    legend.AddEntry(histo, file_names[i], "l")


This gives the following error-

 File "", 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.

As the error says, one index is out of range (most probably xValues[1]), so you should make sure what you get from your text files is what you expect…

So is it some error emerging from split? Here re the text files for reference.
test1.txt (6.3 KB)
test2.txt (64.5 KB)
test3.txt (64.2 KB)
test4.txt (67.3 KB)
test5.txt (63.2 KB)

You’re filtering with:

if "Time" in l or "LECROY" in l or "Segment" in l or "#" in l or "," not in l:

and there is no comma (,) in your text files…