# Filling a histogram with content of two other histograms at different x-axis ranges

Dear all,
I have two 1D histograms h1 ( from 0 to 120 and bin number 14) and h2 (from 5 to 120 and bin number 19).
I want create and fill a third histogram h3 with the content of h1 from x-axis range 0-20 and the content of h2 above 20 to 120.

Here is what I am trying to do:

``````TH1D *h3 = new TH1D("h3","h3", 19, 0, 120);

for (Int_t i=0; i<=20; i++){
float content = h1->GetBinContent(i);
float error = h1->GetBinError(i);
h3->SetBinContent(i,content);
h3->SetBinError(i,error);
}

for (Int_t j=20; j<=120; j++){
float contentt = h2->GetBinContent(j);
float errorr = h2->GetBinError(j);
h3->SetBinContent(j,contentt);
h3->SetBinError(j,errorr);
}
``````

But I am not getting the right histogram. Can someone help?

Regards,
Haidar.

You loop over the bins. They are numbered from 1 to N

1st loop should be:

``````for (Int_t i=1; i<=14; i++){
``````

2nd loop should be:

``````for (Int_t j=1; j<=19; j++){
``````

Also that might not work. Because:

h1 has 14 bins from 0 to 120
h2 has 19 bins from 5 to 120

You created h3 with 19 bins from 0 to 120 … the range is fine because it include both h1 and h2 but the number of bins is problematic.
Just take bin 1 from h1 and bin 1 from h3: They do not match because h1 has 14 bins and h3 19 …

Let me modify my problem like this:

``````TH1D *h1 = new TH1D("h1","",100,0,120);
TH1D *h2 = new TH1D("h2","",100,0,120);
TH1D *h3 = new TH1D("h3","",100,0,120);//they have same bins

h1->FillRandom("pol2",1000);
h2->FillRandom("landau",1000);//just arbitrary functions
``````

Now the question is, how to fill h3 with h1 (using its content from 0 to 20 only) and h2 (using its content from 20 to 120)?

``````{
auto C = new TCanvas("C","C",600,800);
C->Divide(1,3);
TH1D *h1 = new TH1D("h1","",100,0,120);
TH1D *h2 = new TH1D("h2","",100,0,120);
TH1D *h3 = new TH1D("h3","",100,0,120);

h1->FillRandom("landau",1000);
h2->FillRandom("pol2",1000);

int h1bin1 = h1->FindBin(0.);
int h1bin2 = h1->FindBin(20.);
int h2bin1 = h2->FindBin(20.);
int h2bin2 = h2->FindBin(120.);

for (Int_t i=h1bin1; i<=h1bin2; i++){
float content = h1->GetBinContent(i);
float error = h1->GetBinError(i);
h3->SetBinContent(i,content);
h3->SetBinError(i,error);
}

for (Int_t j=h2bin1; j<=h2bin2; j++){
float contentt = h2->GetBinContent(j);
float errorr = h2->GetBinError(j);
h3->SetBinContent(j,contentt);
h3->SetBinError(j,errorr);
}

C->cd(1); h1->Draw();
C->cd(2); h2->Draw();
C->cd(3); h3->Draw("hist");
}
``````

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