Normalize Histogram

Normalizing a Histogram

Image produced by .x NormalizeHistogram.C Two different methods of normalizing histograms are shown, each with the original histogram. next to the normalized one.

Author: Advait Dhingra
This notebook tutorial was automatically generated with ROOTBOOK-izer from the macro found in the ROOT repository on Thursday, May 19, 2022 at 08:14 AM.

In [1]:
%%cpp -d
#include "TH2F.h"
#include "TRandom.h"
#include "TCanvas.h"
In [2]:
std::array<double, 6> binsx{0, 5, 10, 20, 50, 100};
TH1F *orig = new TH1F("orig", "Original histogram before normalization", binsx.size() - 1, &binsx[0]);

gStyle->SetTitleFontSize(0.06);

TRandom2 rand;

Filling histogram with random entries

In [3]:
for (int i = 0; i < 100'000; ++i) {
   double r = rand.Rndm() * 100;
   orig->Fill(r);
}

TH1F *norm = (TH1F *)orig->Clone("norm");
norm->SetTitle("Normalized Histogram");
Unbalanced braces. This cell was not processed.

Normalizing the histogram by scaling by 1 / the integral and taking width into account

In [4]:
norm->Scale(1. / norm->Integral(), "width");
input_line_54:2:2: error: reference to overloaded function could not be resolved; did you mean to call it?
 norm->Scale(1. / norm->Integral(), "width");
 ^~~~
/usr/include/c++/9/complex:690:5: note: possible target for call
    norm(const complex<_Tp>& __z)
    ^
/usr/include/c++/9/complex:1864:5: note: possible target for call
    norm(_Tp __x)
    ^

Drawing everything

In [5]:
TCanvas *c1 = new TCanvas("c1", "Histogram Normalization", 700, 900);
c1->Divide(1, 2);

c1->cd(1);
orig->Draw();
c1->cd(2);
norm->Draw();
input_line_55:8:1: error: reference to overloaded function could not be resolved; did you mean to call it?
norm->Draw();
^~~~
/usr/include/c++/9/complex:690:5: note: possible target for call
    norm(const complex<_Tp>& __z)
    ^
/usr/include/c++/9/complex:1864:5: note: possible target for call
    norm(_Tp __x)
    ^

Draw all canvases

In [6]:
%jsroot on
gROOT->GetListOfCanvases()->Draw()