Retrieving an unnamed TGraph

Just note that there will be an additional “action” required if, instead of TGraph objects, you try to retrieve TH* objects (and similar) using “GetObject” or “Get” (i.e., something like: “if (o) f->Remove(o);”) → see: Broken TDirectoryFile::FindObjectAny and TDirectoryFile::FindKeyAny - #11 by pcanal

A complete toy example dealing with some TH1D histograms:

{
  TString f_name = "toy.root";
  TFile *f;
  
  TString o_name = "h"; // usually "SomeName" or ""
  TH1D *o;
  
  // create the "f_name" ROOT file with a bunch of histograms
  for (Int_t i = 1; i <= 10 ; i++) {
    f = TFile::Open(f_name, ((i > 1) ? "UPDATE" : "RECREATE"));
    o = new TH1D(o_name, TString("sub-sample ") + ((Long_t)i), 100, -3, 3);
    o->FillRandom("gaus", 10000);
    o->Write();
    delete f; // automatically deletes "o"
  }
  
  // analyse histograms from the "f_name" ROOT file
  f = TFile::Open(f_name);
  f->ls();
  THStack *hs = new THStack();
  for (Int_t i = 1; i < 9999 ; i++) { // 9999 = a "memory object"
#if 1 /* 0 or 1 */
    // checks that the object with the given "o_name" is a TH1D
    f->GetObject(o_name + ";" + ((Long_t)i), o);
#else /* 0 or 1 */
    // assumes that any object with the given "o_name" is a TH1D
    o = ((TH1D *)(f->Get(o_name + ";" + ((Long_t)i))));
#endif /* 0 or 1 */
    if (o) f->Remove(o); // needed for TH* and similar objects
    if (!o) break; // no more TH1D found
    hs->Add(o);
  }
  if (hs->GetNhists()) hs->Draw();
}

BTW. If you need to deal with, e.g., TH1F histograms, replace all occurrences of TH1D in this macro with TH1F.