Error on different bin limits when rebinning

Hi,
inside a loop I want to change the binning in a TH1D histogram
which comes from a ProjectionY of a TH2D histogram.

In my header file I declared:
TH1D *tofit;
TH2D *h2temp;

In the .C file I have:

fot (int i=1;i<11;i++){
tofit = 0;

h2temp = (TH2D*)ff.Get(nameth2.str().c_str()); // fill h2temp TH2D histogram

if (i<=9) tofit = h2temp->ProjectionY(“tofit”, i,i);
if (i>9){
tofit = new TH1D(“tofit”,"",nbins/4,xmin,xmax);

      h2temp->Rebin2D(1,4);
      
      tofit = (TH1D*) h2temp->ProjectionY("tofit",  i,i);

}
} //end loop on i

I get the warning and error:
Warning in TFile::Append: Replacing existing TH1: tofit (Potential memory leak).
Warning in TFile::Append: Replacing existing TH1: tofit (Potential memory leak).

Info in : Axes have different bin limits
Error in TH2F::DoProjection: Histogram with name tofit already exists and it is not compatible

However, if I print the GetNbins(), GetXmin(),GetXMax(), of the “tofit” histogram and of h2temp->GetYaxis(),
they are the same.
It seems that the tofit histogram with the new binning has not be "updated"
Can please anybody help me?

Cheers,
Marianna.

Hi,

You should use a different name for the histograms you project. If the histogram already exists (like in the case of “to fit”), it can cause a problem if the histogram is not compatible.

Lorenzo