What’s the best way to plot a portion of a histogram (while preserving error data)?
For instance, I have a histogram with about 16k bins, but I’d like to only plot, say, bins 12200 - 13500. However, this histogram is made from subtracting two other histograms. So it has error data that’s different from the standard Poisson error data, (I assume! If it doesn’t, then I also need to figure out how to make error propagate properly.)
My approach was:
TH1D noBgCounts(counts - bgcounts);
auto noBgCounts_plot = new TH1D("Plot", titleString.c_str(), end_bin - start_bin, start_bin, end_bin);
for (int i = 0; i < end_bin - start_bin; ++i) {
noBgCounts_plot->SetBinContent(i, noBgCounts.GetBinContent(start_bin+i));
}
And then plot noBgCounts_plot, but I’m reasonably certain looking at the return type of GetBinContent that this doesn’t preserve error, so I’m left with the standard sqrt error.
I also need to fix a gaussian to this data (noBgCounts_plot), does the gaussian use the errors on the bins to formulate the errors of its parameters?
Thanks for the help!
{
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);
}