Looping over histograms in memory

Hi,

I am trying to get histograms from a file and then loop over them in order to plot them altogether.

void plot_tallies8(const char* fname)
{
    TFile *f1 = new TFile(fname);
    f1->ls();
    
    TH1F* h1 = (TH1F*) f1->Get("tally_8_3");
    TH1F* h2 = (TH1F*) f1->Get("tally_18_3");
    TH1F* h3 = (TH1F*) f1->Get("tally_28_3");
    TH1F* h4 = (TH1F*) f1->Get("tally_38_3");
    TH1F* h5 = (TH1F*) f1->Get("tally_48_3");
    TH1F* h6 = (TH1F*) f1->Get("tally_58_3");
    TH1F* h7 = (TH1F*) f1->Get("tally_68_3");
    
    Char_t name[20];
    for(Int_t i=0;i<7;i++)
    {
    sprintf(name,"%s%d","h",i);
    TH1F *h = (TH1F*) gDirectory->Get(name);
    if (!h) {cout << "Error. Histogram " << name << " not found" << endl;}
    if (i == 1)
        {if (h) h->Draw("hist");
        cout << "h" << i << endl;}
    else
        {if (h) h->Draw("same");
        cout << "h" << i << endl;}
    }
    
}

From what I see, the

TH1F *h = (TH1F*) gDirectory->Get(name);

line doesn’t retrieve the name since it is looking into the file. How could I retrieve the pointers to my histograms h?

Thanks a lot in advance,

D

Try: TH1F *h = (TH1F*) gDirectory->Get(TString::Format("tally_%d_3", (10 * i + 8)));

1 Like

Thanks a lot! Is there any way to access the histograms h1 - h7? Unfortunately sometimes I will have to deal with histograms with weird names.

h1->Draw("hist"); h2->Draw("hist same"); // ... h7->Draw("hist same");

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.