Problems to fit TGraphErrors


I tried without success to

  • read 48 objects of the type TGraphErrors (no more than 200 points each)
  • fit them with a simple fit-function
  • display the results in a Canvas which has been divided in 8x6 Pads

Everything works fine until I try to display the results. All TGraphErrors have been found and all fits gave resonable results. But every attempt to draw the results (compiled or interpreted) results in an error of TGraph::Paint

The funny thing is: the program works, if I draw only 13 (or less) Objects rather than 48

Is there any stupid, embarrasing error I am unable to find?

Thanks a lot, Jörn.

void testgfit() {
  TGraphErrors* gGraph[48]; 
  TF1*          gFitFn[48];

  // open file with TGraphErrors
  TFile* ff = new TFile ("testg.root");
  if (!ff) { cerr << "can't open testg.root" << endl; return; }

  for (int i=0; i<48; i++) {

    // get the TGraphErrors (works fine, found all)
    char graph_name [80];
    sprintf (graph_name, "L1.%02d", i+1); 
    gGraph[i]=(TGraphErrors*) ff->Get(graph_name);
    if (gGraph[i] == NULL) {
      cerr << "graph " << graph_name << "not found in file" << endl;
    // create the fit function (works fine, created all)
    char funct_name [80];
    sprintf (funct_name, "ftdc%d", i);
    TF1* ftdc = new TF1(funct_name, "[0]+[1]*x+[2]*x*x", 0., 4096.);

    // do the fit (fitError always 0, indicating successful fit)
    int fitError = gGraph[i]->Fit(ftdc,"0q");
    if (fitError) {
      gFitFn[i] = NULL;
      cerr << "fit for " << graph_name << " returns " << fitError << endl;
    // store the function to use it later
    gFitFn[i] = ftdc;

    // all fit parameter very resonable
    cout << i <<  "\t" << gFitFn[i]->GetParameter(1)  
	 << "\t" << gFitFn[i]->GetParameter(2) << endl;
  // create canvas to show the results
  TCanvas* Csec = new TCanvas("Csec", "Csec", 1024, 768);
  Csec->Divide(8, 6, 0.001, 0.001);

  // *** Error caused by TGraph::Paint() *** in this loop
  for (int i=0; i<48; i++) {
    if (gGraph[i]) {
      if (gFitFn[i]) {

testg.root (909 KB)


The cause of your problem is that the TGraphErrors in the file
[ul]- have an existing function (pol2)

  • when the function is restored, it state is not fully restored
  • when the non fully restore function is deleted, it does not inform the TGraphErrors
  • gGraph[i]->Fit(ftdc,“0q”); does delete the existing function[/ul]

A work around is to either prevent the deletion of the existing function:

or to deleted it and purge it explictily:

TF1 *oldf = (TF1*)gGraph[i]->GetListOfFunction()->At(0); if (oldf) { gGraph[i]->GetListOfFunction()->Remove(oldf); delete oldf; }