Read TH1D from .root file via pyROOT


Please read tips for efficient and successful posting and posting code

Please fill also the fields below. Note that root -b -q will tell you this info, and starting from 6.28/06 upwards, you can call .forum bug from the ROOT prompt to pre-populate a topic.

_ROOT Version:6.32.08
_Platform: mac OS 14.7.1 (23H222)
_Compiler:Clang 16.0.0


Hello, I have a program in c++ that produces histograms and saves them as a .png and .root.

TH1F *MW2j = new TH1F("Inv_Mass_2Jets_close_to_W", "Inv. Mass 2 Jets", MW2jHistoParams[0], MW2jHistoParams[1], MW2jHistoParams[2]);
...
...
MW2j->GetXaxis()->SetTitle("GeV");
        MW2j->Draw();
        cout << "Made it. Gotta save it"<< endl;
        c1->SaveAs(FullPathM2jW);
        cout << "boutta save root file" <<endl;
        c1->SaveAs(FullPathM2jW_root);

My goal is to use pyROOT to open histograms and edit them. Eventually, Iā€™d like to combine multiple into a THStack.
The only thing in each .root file should be the histogram. This was my most recent attempt at editing the file and saving it as a new .png

import ROOT


def main():

    histopath = '/work/pi_mjrm_umass_edu/LNV_collider/AnalysisOutput/LNVF/plots/Mass_2jW.root'
    thisHistFile = ROOT.TFile.Open(histopath, "READ")
    canvas = ROOT.TCanvas("test")
    canvas.cd()
    thisHist = thisHistFile.Get("Inv_Mass_2l")
    thisHist.SetLineColor(ROOT.kRed)
    thisHist.Draw()
    print("Printing")
    canvas.print('Work/LNV_collider/AnalysisOutput/test_histo.png')
    

if __name__ == "__main__":
    main()

which gives me this error:

AttributeError: 'TObject' object has no attribute 'SetLineColor'

so it seems my issue is in getting the TH1D as such and not just a general TObject

I realize now that I was saving the canvas and not the histograms. The c++ file now uses

new TFile(FullPathM2jW_root, "RECREATE");
MW2j->Write();
1 Like

Hi Dyson,

Thanks for sharing the outcome of your investigation!

Cheers,
D