Error of undeclared identifier of root file

I am trying to plot stacked histogram but Canvas doesn’t show any plot.

void Analysis(TString file1, TString file2)
{
    THStack hs("hs", "Filtered data for december and January");
    TFile f1(file1);
    TTree* t1 =(TTree*) f1.Get("current_ntuple");
    float_t curr;
    t1->SetBranchAddress("Current", &curr);
    Double_t MinBound = 0;
    Double_t MaxBound = 100;
    Int_t Numbins = 100;

    ULong64_t n = t1->GetEntries();
    TH1D* curr_vals_raw = new TH1D("curr_vals_raw", "Raw current distribution", Numbins, MinBound, MaxBound);
    curr_vals_raw->GetXaxis()->SetTitle("Current [#muA]");
    curr_vals_raw->GetYaxis()->SetTitle("Percentage");
    for (Int_t i = 0; i< n;i++)
    {
        t1->GetEntry(i);
        curr_vals_raw->Fill(curr);
    }
    curr_vals_raw->SetName("Dec Current");
    curr_vals_raw->SetDirectory(0);
    hs.Add(curr_vals_raw);
f1.Close();
    TFile f2(file2);
    TTree* t2= (TTree*) f2.Get("current_ntuple");
    float_t curr2;
    t2 -> SetBranchAddress("Current", &curr2);
    ULong64_t m= t2->GetEntries();
    TH1D* curr_vals_stable = new TH1D("curr_vals_stable", "Stable data Current Distribution", Numbins, MinBound, MaxBound);
    curr_vals_stable->GetXaxis()->SetTitle("Current [#muA]");
    curr_vals_stable->GetYaxis()->SetTitle("Percentage");
    curr_vals_stable->SetLineColor(kRed);
    curr_vals_stable->SetMarkerStyle(7);
    curr_vals_stable->SetName("Stable Current Distribution");
    for (Int_t f = 0; f<m;f++)
    {
        t2->GetEntry(f);
        curr_vals_stable->Fill(curr2);
    }
    curr_vals_stable->SetDirectory(0);
    hs.Add(curr_vals_stable);
f2.Close();


    TCanvas* c1= new TCanvas();
    curr_vals_raw->Draw();
    curr_vals_stable->Draw("same");
    c1->Divide(1,1);
    hs.Draw("nostack");
    TFile outputFile("Decvsjan.root", "recreate");
        curr_vals_raw->Write("Current December");
        curr_vals_stable->Write("Current January");
    outputFile.Close();
}

Try: hs.DrawClone("nostack");

1 Like

Thank You.

Just to clarify, the problem is that the hs variable is declare in the local scope of the Analysis function, so it goes out of scope at the end of the function execution, and gets destroyed (and deregistered from the canvas where it was drawn for a moment).

DrawClone creates a copy of the THStack object the lifetime of which is managed by the ROOT session itself (so it survives the scope of Analysis) and draws that.

An alternative solution is returning the THStack from the Analysis function and call it as auto hs = Analysis("f1.root", "f2.root").

Cheers,
Enrico

1 Like