Subtract two histograms

Hello,
I wish to plot a histogram that is the result of the data in true_110deg_28.txt minus the data in true_background_110deg_28.txt. Both files have the exact same number of bins (2048), but have different number of data points. Does someone know how to do it?

true_110deg_28.txt (315.0 KB)
true_background_110deg_28.txt (190.8 KB)

_ROOT Version:6.23/01

Hi ,
to subtract two histograms you can call, if h1` and ‘h2’ are the pointers for the two histograms and assuming the histograms are of type TH1D:

TH1D * h3 = new TH1D(*h1); 
h3->Add(h2,-1);

h3 will then be the result of h1-h2

Lorenzo

1 Like

I don’t know what I do wrong. When I do the following, I just get the inverse of h2 plotted, not h1-h2.

    TH1D* h1=new TH1D("Statistics" , "Compton Scattering for CS-137" ,2048,0.,2048.);
    h1->SetMarkerStyle(8);
    h1->SetTitle("Compton Scattering for CS-137 (Actual 110 Degrees);Channel Number (Energy);Number of Photons");
    ifstream inp; double y;
    gStyle->SetOptFit(1111);
    inp.open("110deg_28.pdf");
    while(!(inp >> y)==0){h1->Fill(y);}
    
TH1D* h2=new TH1D("Statistics" , "Compton Scattering for CS-137" ,2048,0.,2048.);
h2->SetMarkerStyle(8);
h2->SetTitle("Compton Scattering for CS-137 (Background 110 Degrees);Channel Number (Energy);Number of Photons");
ifstream inps; double x;
gStyle->SetOptFit(1111);
inps.open("true_background_110deg_28.txt");
while(!(inps >> x)==0){h2->Fill(x);}
    
    TH1D * h3 = new TH1D(*h1);
    h3->Add(h2,-1);
    h3->Draw();

Hi Edward,

this

can’t be right, can it?
But the main problem is I think with

– try changing this into

TH1D * h3 = (TH1*)h1->Clone("h3");
1 Like

@yus. This line

TH1D * h3 = new TH1D(*h1);

is correct.

After fixing the input file the code works for me

Lorenzo

1 Like

Ah ok, I just wrote the input file incorrectly, thank you all!