TH1 fit out of range

I have a very simple macro which opens histograms from a root file and should fit them with a gaussian, but whenever I try to fit them I get

Warning in <ROOT::Fit::FillData>: fit range is outside histogram range, no fit data for xaxis
Warning in <Fit>: Fit data is empty 

Here’s my code:

void MyMacro(){

  TFile *_file0 = TFile::Open("MyRootFile.root");

  //Histograms per channel
  TH1F *hMyHisto;

  //Canvases for histograms
  TCanvas *cMyCanvas = new TCanvas("cMyCanvas","cMyCanvas",1800,1400);
  cMyCanvas->Divide(10,7);

  //Maximum bins, around which to do fit 
  Int_t MyMaxBin;
  Double_t MyMaxVal;
  
  //Fit function
  TF1 *gausfit = new TF1("Mygausfit","gaus(0)");
  
  //Fit result pointer
  TFitResultPtr fitMyResult;

  std::string name;

  for(int ChID = 20; ChID<90; ChID++){
    cMyCanvas->cd(ChID-19);

    //get timediff histograms from rootfile
    name = Form("MyHisto%i",ChID);  
    hMyHisto = (TH1F*)_file0->Get(name.c_str());

    if(!hMyHisto){
      std::cout<<"No hMyHisto"<<std::endl;
      continue;
    }
    hMyHisto->Draw();
    MyMaxBin = hMyHisto->GetMaximumBin();
    MyMaxVal = hMyHisto->GetMaximum();

    gausfit->SetRange(MyMaxVal-0.5,MyMaxVal+0.5);
    gausfit->SetLineColor(kRed);
    gausfit->SetParameter(1,MyMaxVal);
    gausfit->SetParameter(2,1.);
    fitMyResult = hMyHisto->Fit("gausfit","BQRS");
  }

}

I solved it for myself - TH1::GetMaximum() gets the BinContent of the bin with the most entries, not as I thought the value of the X coordinate of the maximum bin. Therefore the correct range is:

MyMaxVal = hMyHisto->GetXaxis()->GetBinCenter(GetMaximum());
gausfit->SetRange(MyMaxVal-0.5,MyMaxVal+0.5);

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.