Help with Subtracting two TH1D histograms

Hi, I am trying to subtract two TH1D histograms using the following:

[code]TFile *f1 = TFile::Open(“hist.root”);
TH1D h1 = (TH1D) f1->FindObjectAny(“c1”);

TFile *f2 = TFile::Open(“hist1.root”);
TH1D h2 = (TH1D) f2->FindObjectAny(“c2”);


but the output is the original h1 histogram and not the difference of the two. Your help is appreciated.

1 Like

Could you post your 2 root files?


Here they are:

Your files contain a TCanvas, in turn containing a TH1D.
You should probably do something like:

TFile *f1 = TFile::Open("…/Downloads/Run08042_ProjectionX.root");
TCanvas c1 = (TCanvas)f1->Get(“c1”);
TH1D h1 = (TH1D)c1->FindObject(“cutg”);
TFile *f2 = TFile::Open("…/Downloads/Run08044_ProjectionX.root");
TCanvas c2 = (TCanvas)f1->Get(“c1”);
TH1D h2 = (TH1D)c2->FindObject(“cutg”);



When I use the code you posted and then

h1.Draw() no canvas or histogram appears. Thank you.

simply create a new canvas as shown below. I notice that your 2 histograms named “cutg” are identical in the 2 canvases.


TCanvas *c3 = new TCanvas("c3"); h1->Draw();

Thanks for your help; I got the following code to work:

TFile *f2 = TFile::Open("Run08042_ProjectionX.root");//0.87*[8044]-[8042] TCanvas *c2 = (TCanvas*)f2->Get("c1"); TH1D *h2 = (TH1D*)c2->FindObject("8042"); TFile *f1 = TFile::Open("Run08044_ProjectionX.root"); TCanvas *c1 = (TCanvas*)f1->Get("c2"); TH1D *h1 = (TH1D*)c1->FindObject("8044"); h1.Scale(0.87) h1->Add(h2,-1); TCanvas *c3 = new TCanvas("c3");

Hi I have to do something similar but when I try the same code written here to subtract histograms i get the following error
Error: illegal pointer to class object c2 0x0 75 (tmpfile):1:
*** Interpreter error recovered ***

What to do ?

An 0x0 pointer kind of an internal ROOT equivalent of a null pointer, so you can’t dereference it to draw or call other methods, because it doesn’t point to anything useful.

Generally getting a 0x0 pointer means that the FindObject/GetPrimitive/etc method couldn’t find the thing you named. Check that the name is correct and that the file actually contains it (it’s relatively easy to check interactively with a TBrowser for example).