# Help with linear fit

Hello, I need help with a very simple problem: a linear fit. I don’t understand what is wrong with this code… The data shows up on the graph but not the fit…

``````#include "TCanvas.h"
#include "TFile.h"
#include "TH1.h"
#include "TF1.h"
#include "TAxis.h"
#include "TStyle.h"
#include <cmath>
#include <string>
#include <iostream>
using namespace std;

void linearfitcal(){
gStyle->SetOptFit(1111);
TCanvas *canvas=new TCanvas("canvas", "canvas", 800, 800);

double x[3] = {196.45, 251,300};
double ex[3]={0.198,0.210,0.154};
double y[3]={0.02860271,0.0286013,0.02860063};
double ey[3]={0};

TGraphErrors *gr = new TGraphErrors(3,x,y,ex,ey);
gr->SetMarkerStyle(24);
gr->SetMarkerSize(0.5);
gr->Draw("AP");

TF1 *fitFunc = new TF1("fitFunc", "pol1");
//TF1 *fitFunc = new TF1("fitFunc", "expo");
fitFunc->SetParName(0, "Intercept");
fitFunc->SetParName(1, "Slope");
//fitFunc->SetParameter(0,-8);
//fitFunc->SetParameter(1,0.1);

gr->Fit("fitFunc", "R");

gr->SetTitle("Calibrazione;#Deltax [nm];#Delta#lambda_{r.u.}");

TCanvas *canvas1=new TCanvas("canvas1", "canvas", 800, 800);
TGraphErrors *residual= new TGraphErrors;

for (int i=0; i<3; i++){
residual->SetPoint(i , x[i], y[i]-fitFunc->Eval(x[i]));
Double_t eyr = gr->GetErrorY(i);
residual->SetPointError(i, 0, eyr);

}

residual->SetTitle("Residuals;#Deltax [nm];data_{meas} - data_{fit}");
residual->SetMarkerStyle(21);
residual->Draw("ape");

// Determine the range of the residual plot
double xmin = residual->GetXaxis()->GetXmin();
double xmax = residual->GetXaxis()->GetXmax();

// Draw a dotted horizontal line at y=0 within the range of the residual plot
TLine *line = new TLine(xmin, 0, xmax, 0);
line->SetLineStyle(2); // Dotted line style
line->Draw();

return;
}

``````

Probably you should Fit before you Draw. ROOT does not automatically update the drawing just because you did a fit.

Hi,

Your fit does not work, first of all you are using option “R”, which should be removed in your case. Then fitting a TGraphErrors, the fit is not linear and you need to provide initial parameter values.
I would suggest you first to fit ignoring the x error (in this case the fit is linear) and then fitting including the x errors. This can be done by doing:

``````gr->Fit("fitFunc", "EX0");
gr->Fit("fitFunc", "");
``````

However, the final fit seems not to work well, probably because the given errors do not make much sense.

@sfpate, ROOT by default redraws your histogram (or graph) with the fitted function after doing a fit.

Lorenzo

Thank you for the suggestion! Yes, the data is a bit problematic so I don’t think there’s much to do… but still thanks a lot!