Drawing ROOT Histogram from File is empty

Please read tips for efficient and successful posting and posting code

ROOT Version: 6.20/04
Platform: Ubuntu18.04
Compiler: gcc

I read histogram from a root file. I make sure that the title and the number of entries is correct (cout <<). But when I do ->Draw(), the title shows, but there is no histogram and no axis labels. Here is my code:

#pragma once
#include <TFile.h>
#include <TH1.h>
#include <TCanvas.h>
#include <TPad.h>
#include <TFrame.h>
#include <TROOT.h>
#include <TSystem.h>
#include "TDirectory.h"
#include "TMath.h" 
#include <iostream>
#include <fstream>
#include <iomanip>
#include <math.h>

void run() {
    TFile f("dqm.e18.r66-277.root") ;
    f.cd("TRGCDCTNN") ;
    f.ls() ;
    TH1F *NeuroHWOutZ = (TH1F*)gDirectory->Get("NeuroHWOutZ"); 
    cout << " Title of Histogram: " << NeuroHWOutZ->GetTitle() << ", Nev = " << NeuroHWOutZ->GetEntries() << " ,  mean = " << NeuroHWOutZ->GetMean() << std::endl ;

    TCanvas *c01 = new TCanvas("c01","NNPlots",1000,800);
    c01->Divide(2,1) ;
    c01->cd(1) ;
    NeuroHWOutZ->Draw() ;
    c01->Update() ;
    c01->cd(2) ;
    TH1F *H1 = (TH1F*)NeuroHWOutZ->Clone(); 
    cout << " Title of Clone    : " << H1->GetTitle() << ", Nev = " << H1->GetEntries() << " ,  mean = " << H1->GetMean() << std::endl ;
    H1->Draw() ;
    c01->Update() ;

The same as above happens for the cloned histo: title/entries OK, no histogram displayed

What am I missing in my code?

Two options:

1 - Make f a pointer:
TFile *f = new TFile("myfile.root") ;

2 - or “unlink” the histos from f (if it is not a pointer) before drawing them:


Hello, thanks for the help.
If I make f a pointer, this is the result:

root [0] .L test.C+
Info in TUnixSystem::ACLiC: creating shared library /home/cmk/CCMK/basf2/phase3/neuro/remote/lumidat/neurodqm/./test_C.so
In file included from input_line_11:6:
././test.C:20:12: error: cannot initialize a variable of type ‘TFile *’ with an lvalue of type ‘const char [21]’
TFile *f(“dqm.e18.r66-277.root”) ;

However, if I use your second method (unlinking), everything works!
Thanks a lot!

ps Is there any explanation for the failure when the pointer is used?


as @dastudillo pointed out, it’s not enough to do

TFile *f("dqm.e18.r66-277.root");

instead of your

TFile f("dqm.e18.r66-277.root");

– you should instead do

TFile *f = new TFile("dqm.e18.r66-277.root");

thanks, I overlooked this subtle detail:

TFile *f = new TFile("dqm.e18.r66-277.root");

now everything works, and I do not need to issue “xxx->SetDirectory(0)”
Solution 1 is the preferred one