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;
}