I’m trying to perform a simple linear fit but the parameters I get are both equal to zero. I previously used this code for another set of data and it worked, so I really don’t understand what I’m doing wrong
#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 calibrazione() {
gStyle->SetOptFit(0011);
TCanvas *canvas=new TCanvas("canvas", "canvas", 800, 800);
string names[4] = {"Na 1", "Na 2", "Co 1", "Co 2"}; // Names for each data point
double x[4] = {2798.3,6732.3,6179,6988};
double y[4] = {511,1274, 1173.2,1332.5};
double ex[4]={0.3,0.8,1,1};
double ey[4]={0};
TGraphErrors *gr = new TGraphErrors(4,x,y,ex,ey);
gr->SetMarkerStyle(21);
gr->SetMarkerSize(1);
gr->Draw("ape");
TF1 *fitFunc = new TF1("fitFunc", "pol1");
gr->Fit("fitFunc");
gr->SetTitle("Calibration; Position; Energy [keV]");
// Add labels for each data point
for (int i = 0; i < 4; i++) {
double xpos1 = x[i];
double ypos1 = y[i]+50;
TString label1 = names[i].c_str();
TLatex *latex1 = new TLatex(xpos1, ypos1, label1);
latex1->SetTextSize(0.02);
latex1->SetTextAlign(22);
latex1->Draw();
}
canvas->Update();
TCanvas *canvas1=new TCanvas("canvas1", "canvas", 800, 800);
TGraphErrors *residual= new TGraphErrors;
for (int i=0; i<4; 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("Residui (ch0)");
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();
// Add labels for each data point
for (int i = 0; i < 4; i++) {
double xpos = x[i]+0.0006;
double ypos = y[i] - fitFunc->Eval(x[i]);
TString label = names[i].c_str();
TLatex *latex = new TLatex(xpos, ypos, label);
latex->SetTextSize(0.02);
latex->SetTextAlign(22);
latex->Draw();
}
return;
}