Problem with Graph saving

Hello all,

I am new here, I tried to save my graph into my .root file, but an error Error in TGraph::Write: No file open occurs.

The code is as follow:


TFile* hfile = new TFile(“mymcfilehist.root”, “RECREATE”);
TGraph* gr1 = new TGraph(bins);


for (Int_t j=0; j<bins; ++j) {
gr1->SetPoint(j,binning[j],gr1Entries[j]);
}


gr1->Write();
hfile->Write();

Thanx for any comment, I really don’t know why it isn’t working. :confused:

Tomas

This works for me:

Macro graph.C:

{
   gROOT->Reset();
   c1 = new TCanvas("c1","A Simple Graph Example",200,10,700,500);

   gfile = new TFile("gsimple.root","RECREATE","Graph file");

   const Int_t n = 20;
   Double_t x[n], y[n];
   for (Int_t i=0;i<n;i++) {
     x[i] = i*0.1;
     y[i] = 10*sin(x[i]+0.2);
   }
   gr = new TGraph(n,x,y);
   gr->SetTitle("a simple graph");
   gr->Draw("AL");

   gr->GetHistogram()->SetXTitle("X title");
   gr->GetHistogram()->SetYTitle("Y title");

   gr->Write();
}

output:

pcepsft15> root
  *******************************************
  *                                         *
  *        W E L C O M E  to  R O O T       *
  *                                         *
  *   Version   4.00/03     13 April 2004   *
  *                                         *
  *  You are welcome to visit our Web site  *
  *          http://root.cern.ch            *
  *                                         *
  *******************************************

FreeType Engine v2.1.3 used to render TrueType fonts.
Compiled for linux with thread support.

CINT/ROOT C/C++ Interpreter version 5.15.131, Apr 6 2004
Type ? for help. Commands must be C++ statements.
Enclose multiple statements between { }.
root [0] .x graph.C              
root [1] .q
pcepsft15> root     
  *******************************************
  *                                         *
  *        W E L C O M E  to  R O O T       *
  *                                         *
  *   Version   4.00/03     13 April 2004   *
  *                                         *
  *  You are welcome to visit our Web site  *
  *          http://root.cern.ch            *
  *                                         *
  *******************************************

FreeType Engine v2.1.3 used to render TrueType fonts.
Compiled for linux with thread support.

CINT/ROOT C/C++ Interpreter version 5.15.131, Apr 6 2004
Type ? for help. Commands must be C++ statements.
Enclose multiple statements between { }.
root [0] TFile f("gsimple.root");
root [1] Graph->Draw("AL");      
<TCanvas::MakeDefCanvas>: created default TCanvas with name c1
root [2] 

Hi,

This kind of error could happen if you change the current ROOT directory.
You should be able to fix the problem by just doing:

hfile->cd(); gr1->Write(); hfile->Write();

Cheers,
Phlippe