{
gStyle->SetOptFit();
TH1::SetDefaultSumw2(kTRUE); // ensure proper error propagation
TH1D *counts = new TH1D("counts", "full histogram", 100, -5, 5);
// counts->Sumw2(kTRUE); // not needed if "TH1::SetDefaultSumw2"
counts->FillRandom("gaus", 11000);
TH1D *bgcounts = new TH1D("bgcounts", "background", 100, -5, 5);
// bgcounts->Sumw2(kTRUE); // not needed if "TH1::SetDefaultSumw2"
bgcounts->FillRandom("gaus", 1000);
TH1D *noBgCounts = new TH1D(*counts); // make a copy of "counts"
noBgCounts->SetNameTitle("noBgCounts", "full histogram - background");
// noBgCounts->Sumw2(kTRUE); // not needed if "TH1::SetDefaultSumw2"
noBgCounts->Add(bgcounts, -1.0); // subtract "bgcounts"
TCanvas *c = new TCanvas("c", "c");
c->Divide(2, 2);
c->cd(1);
counts->Draw();
c->cd(2);
bgcounts->Draw();
c->cd(3);
noBgCounts->DrawCopy(); // "DrawCopy" because we change its "range" below
c->cd(4);
// set the viewing range for the X axis
#if 0 /* 0 or 1 */
Int_t start_bin = 30, end_bin = 70;
noBgCounts->GetXaxis()->SetRange(start_bin, end_bin); // "bin numbers"
#else /* 0 or 1 */
Double_t xmin = -2, xmax = 2;
noBgCounts->GetXaxis()->SetRangeUser(xmin, xmax); // "user coordinates"
#endif /* 0 or 1 */
// noBgCounts->Draw();
noBgCounts->Fit("gaus");
c->cd(3);
noBgCounts->GetFunction("gaus")->Draw("SAME");
c->cd(0);
}