Shift along x-axis an existing TProfile keeping the uncertainty bars

Hello all,
I’m trying without success to load a TProfile inside a .root file, rescaling it to its maximum and shifting it to have a new TProfile with the same features as the first one but shifted to have the peak in x=0.
I succeeded in shifting and normalizing it but the uncertainty bars vanish, or they become too large.
What I guess it’s the function SetBinError is not working properly.
I’ll attach a version of my code that does it and a couple of screenshots of the output.
Thanks in advance for the help.

Code:


#include <TFile.h>
#include <TProfile.h>
#include <TCanvas.h>
#include <TLegend.h>
#include <TString.h>
#include <iostream>

using namespace std;

void template_shifter() {
    TString profile_path = "/path/";
    TString filenames =   profile_path + "template_library2.root";
    
    TFile *file = TFile::Open(filenames);

    TFile *outputFile = new TFile(profile_path + "shifted_templates.root", "RECREATE");


    for(Int_t i =1;i<=4;i++){
        TProfile *profile = (TProfile*)file->Get(Form("template_mcp_ch00%d",i));

        int max_bin = profile->GetMaximumBin();
        double max_position = profile->GetBinCenter(max_bin);
        double max_value = profile->GetBinContent(max_bin);

        profile->Write();
        profile->Scale(1./max_value);
        TProfile *shiftedProfile = new TProfile(Form("shifted_template_mcp_ch00%d", i), profile->GetTitle(), profile->GetNbinsX(), -max_position, profile->GetXaxis()->GetXmax() - max_position);

        // Shift del profilo
        for (int bin = 1; bin <= profile->GetNbinsX(); bin++) {
            double original_bin_center = profile->GetBinCenter(bin);
            double shifted_bin_center = original_bin_center - max_position;
            double bin_content = profile->GetBinContent(bin);
            double bin_error = profile->GetBinError(bin)/max_position;
            shiftedProfile->Fill(shifted_bin_center, bin_content);
            shiftedProfile->SetBinError(shifted_bin_center, bin_error);
        }
        shiftedProfile->Write();
    }
    
outputFile->Close();
file->Close();
exit(0);
}

Loaded TProfile:

Output:

ROOT Version: 6.26/11
Compiler: g++ (GCC) 11.4.1

Thank you for your question @erFross
Let me add @moneta in the loop.

Cheers,
Devajith

Have you tried to use SeBinContent instead of Fill ?

Hello, thanks for the answers.
Yes, I tried but no difference

Hello,
For a TProfile you cannot call SetBinError and SetBinContent since both the content and the errors are computed on the fly with the existing information. You need to set the correct bin sum of y values, bin sum of y square and number of bin entries. If the TProfile is weighted you nedd also the bin sum of weight square.
Here is an example code to copy the TProfile information. You can use a sstarting point to shift the content horizontally

Lorenzo

CopyTProfile.C (1.3 KB)