Pyroot draw line on subplot histogram

I want to draw a vertical TLine on each subpad of my TCanvas. The plots have different vertical ranges, so I define a function to create the TLine with the correct height for each plot, but when I go to draw the line it only gets drawn on the very last plot in the pad.

MWE:

import ROOT, os
from ROOT import TFile, TH1F, kGreen

def tline(x1,y1,x2,y2,colour):
    line = ROOT.TLine(x1,y1,x2,y2)
    line.SetLineColor(colour)
    return line

run_no = 50440
file_path=os.path.join("HistoFile.root")


root_file = ROOT.TFile(file_path,"read")

x_channels = [8,7,9,6,10,5,11,4,12,3,13,2,14,1,15,0]

histos_x=([root_file.Get(f"MyHistos{ch}") for ch in x_channels])

canvas_x = ROOT.TCanvas("canvas_x","canvas_x",1800,1400)
canvas_x.Divide(4,4)

for i_plot in range(16):
    canvas_x.cd(i_plot+1)
    x_histo=histos_x[i_plot]
    x_histo.Draw()
    x_histo.SetTitle(";;")
    x_vertical_zero_line = tline(0,0,0,1.05*x_histo.GetMaximum(),kGreen)
    x_vertical_zero_line.Draw()

canvas_x.Modified()
canvas_x.Update()

This line should give you an error:

    canvas_x(i_plot+1)

so I don’t think your example even runs. Anyway, that line should be

    canvas_x.cd(i_plot+1)

yes sorry, after copying and pasting the code I made some edits to the names of variables etc and accidentally deleted the .cd. I’ve edited the code

Try

    x_vertical_zero_line.DrawClone()

This doesn’t show the line at all on any of the plots

This

import ROOT, os
from ROOT import TFile, TH1F, kGreen

def tline(x1,y1,x2,y2,colour):
    line = ROOT.TLine(x1,y1,x2,y2)
    line.SetLineColor(colour)
    return line

canvas_x = ROOT.TCanvas("canvas_x","canvas_x",900,900)
canvas_x.Divide(3,3)

for i_plot in range(9):
    canvas_x.cd(i_plot+1)
    x_vertical_zero_line = tline(0,0,0,0.8,kGreen)
    x_vertical_zero_line.DrawClone()

canvas_x.Modified()
canvas_x.Update()

gives me this:

So the basic code works and your error is somewhere else, maybe you are not actually reading or plotting the histograms, etc. Check that the other parts work.

Your code for me gives me this, a single long green line on the left
For context: python3.12, macos 14.4.1

PS in the real code, just below the line.Draw() I have a histo.Fit() which works fine.

Is anyone able to reproduce this effect?

Dear @bethlong06 ,

Thank you for reaching out to the forum! I believe your problem does not really depend on the Python version or the platform. Can you try to create a list that will hold the TLine objects before the loop and then append the TLine objects you create inside the loop? e.g.


lines = []
for i_plot in range(16):
    canvas_x.cd(i_plot+1)
    x_histo=histos_x[i_plot]
    x_histo.Draw()
    x_histo.SetTitle(";;")
    x_vertical_zero_line = tline(0,0,0,1.05*x_histo.GetMaximum(),kGreen)
    lines.append(x_vertical_zero_line)
    x_vertical_zero_line.Draw()

Let me know if this works.

Yes this works! Thank you!