Subtract one histogram from another histogram

I have two histograms, let’s say one named "“NAME1” and the other “NAME2”. How do I subtract one histogram from the other and find the difference between the two histograms in a new histogram called “DIFFERENCE”?

Hi @ERYI20 and welcome on the root forum.
You can use the TH1::Add() method of TH1 for this task.
The code should be like this.

difference->Add(name1,name2,1,-1);

Best,
Dilicus

Thanks for your answer. I used your command for a 2D hsitogram, and I am getting an unexpected output from the subtracted histogram. Could you tell me if the bins or something else should be considered in the subtracted histograms?

Could you please be more specific on the unexpected result you are obtaining?
In any case the 3 histogram you are using should have the same binning

I mean, the number of entries in the subtracted histogram is greater than the individual histograms. I also used the same bins for all three histograms.

This is how the number of entries of the new histogram is computed.

 Double_t nEntries = TMath::Abs( c1*h1->GetEntries() + c2*h2->GetEntries() );

I do not know if this explain your issue.

In this case, are we adding rather than subtracting the two histograms (h1 and h2)?

It depends from c1 and c2. Since you pass c1 equal to 1 and c2 equal to -1, the instruction in your case becomes

TMath::Abs (1* name1->GetEntries() + (-1)*name2->GetEntries() )

So your expected number of entries should be equal to the absolute value of the entries of name1 minus the entries of name2.

1 Like

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