Histograms
Histograms are among the most frequently used tools in experimental physics. ROOT provides a comprehensive collection of histogram classes for constructing, manipulating, visualising and analysing distributions.
Learning objectives
After completing this chapter, you should be able to:
- Construct and fill histograms.
- Understand bin numbering and bin contents.
- Work with weighted observations.
- Normalise and compare distributions.
- Visualise and store histograms.
ROOT histogram classes
ROOT provides several histogram classes, depending on the dimensionality and numerical representation of the bin contents.
Class hierarchy
flowchart TD
A["TH1"] --> B["TH1C"]
A --> C["TH1S"]
A --> D["TH1I"]
A --> E["TH1F"]
A --> F["TH1D"]
A --> G["TH2"]
A --> H["TH3"]
G --> I["TH2F"]
G --> J["TH2D"]
H --> K["TH3F"]
H --> L["TH3D"]
The diagram shows a simplified selection of the ROOT histogram class hierarchy.
Commonly used histogram classes
| Class | Dimensions | Bin content type |
|---|---|---|
TH1C |
1 | Character-sized integer |
TH1S |
1 | Short integer |
TH1I |
1 | Integer |
TH1F |
1 | Single-precision floating point |
TH1D |
1 | Double-precision floating point |
TH2F |
2 | Single-precision floating point |
TH2D |
2 | Double-precision floating point |
TH3F |
3 | Single-precision floating point |
TH3D |
3 | Double-precision floating point |
The numerical type refers to the representation of the bin contents, not the type of the observations passed to the histogram.
Which class should I use?
For most scientific analyses, TH1D and TH2D
are appropriate choices.
They provide double-precision bin contents, which are particularly useful when working with weighted observations and normalised distributions.
Creating a one-dimensional histogram
The TH1D class represents a one-dimensional
histogram with double-precision bin contents.
#include <TH1D.h>
A histogram with uniform binning can be constructed using the following syntax:
TH1D histogram(
name,
title,
number_of_bins,
x_min,
x_max
);
For example:
TH1D h(
"h_pt",
"Transverse momentum",
100,
0.0,
10.0
);
Constructor parameters
| Argument | Description |
|---|---|
"h_pt" |
Internal ROOT object name |
"Transverse momentum" |
Histogram title |
100 |
Number of bins |
0.0 |
Lower boundary |
10.0 |
Upper boundary |
The object name is used to identify the histogram within ROOT.
The title is primarily used for visualisation.
Setting axis titles
Axis titles can be specified directly in the histogram title using semicolons.
TH1D h(
"h_pt",
"Transverse momentum;p_{T} [GeV/c];Counts",
100,
0.0,
10.0
);
The title string follows the structure:
Histogram title;X-axis title;Y-axis title
Alternatively, the axis titles can be set using the corresponding axis objects.
h.GetXaxis()->SetTitle("p_{T} [GeV/c]");
h.GetYaxis()->SetTitle("Counts");
Filling a histogram
The Fill() method adds an observation to
the histogram.
h.Fill(2.5);
ROOT determines which bin contains the value and increases its content by one.
Consider the following example:
TH1D h("h", "Example;x;Counts", 5, 0, 10);
h.Fill(0.5);
h.Fill(1.2);
h.Fill(2.8);
h.Fill(3.1);
h.Fill(3.9);
h.Fill(5.2);
h.Fill(8.7);
The resulting bin contents are:
| Bin | Interval | Content |
|---|---|---|
| 1 | \([0,2)\) | 2 |
| 2 | \([2,4)\) | 3 |
| 3 | \([4,6)\) | 1 |
| 4 | \([6,8)\) | 0 |
| 5 | \([8,10)\) | 1 |
Filling a histogram inside a loop
Histograms are commonly filled while processing observations stored in arrays, vectors or trees.
#include <vector>
#include <TH1D.h>
std::vector<double> values = {
0.5, 1.2, 2.8, 3.1, 3.9, 5.2, 8.7
};
TH1D h("h", "Distribution", 5, 0, 10);
for (double value : values)
{
h.Fill(value);
}
The same principle is used when processing experimental datasets containing millions of observations.
Bin numbering
Unlike conventional C++ arrays, the first regular
bin of a ROOT histogram has index 1.
ROOT also reserves two additional bins:
- The underflow bin.
- The overflow bin.
For a histogram containing \(M\) regular bins:
| Bin index | Meaning |
|---|---|
0 |
Underflow |
1 |
First regular bin |
2 |
Second regular bin |
... |
Intermediate bins |
M |
Last regular bin |
M + 1 |
Overflow |
Accessing histogram bins
ROOT provides several methods for accessing individual bins and their properties.
int bin = h.FindBin(3.5);
The FindBin() method determines the bin
corresponding to the specified coordinate.
For an existing bin index:
double content = h.GetBinContent(bin);
double centre = h.GetBinCenter(bin);
double width = h.GetBinWidth(bin);
double lower = h.GetBinLowEdge(bin);
double error = h.GetBinError(bin);
Iterating over histogram bins
for (int i = 1; i <= h.GetNbinsX(); i++)
{
std::cout
<< h.GetBinCenter(i) << " "
<< h.GetBinContent(i) << '\n';
}
This loop accesses only the regular bins.
To include underflow and overflow, use indices
from 0 to GetNbinsX() + 1.
Bin index versus coordinate
A bin index identifies a particular bin.
A coordinate represents a physical value.
These quantities must not be confused.
h.GetBinContent(3);
returns the content of the third regular bin, not necessarily the bin containing the physical value three.
Variable-width bins
Not all histograms require uniform binning.
ROOT also supports histograms with explicitly specified bin boundaries.
double edges[] = {
0.0,
0.5,
1.0,
2.0,
5.0,
10.0
};
TH1D h(
"h",
"Variable-width histogram",
5,
edges
);
The number of boundaries must be one greater than the number of bins.
Variable-width bins can be useful when the density of observations changes significantly across the histogram range.
Comparing variable-width bins
Wider bins generally collect more observations than narrower bins.
When comparing the density of observations, the bin contents should be divided by their corresponding bin widths.
Statistical quantities
ROOT histograms provide methods for calculating several statistical properties of the underlying distribution.
Number of entries
double entries = h.GetEntries();
For a histogram filled exclusively using Fill(),
this generally corresponds to the number of
filling operations.
Mean
double mean = h.GetMean();
Standard deviation
double stddev = h.GetStdDev();
Standard error of the mean
double meanError = h.GetMeanError();
Stored statistics
ROOT normally accumulates statistical sums
during calls to Fill().
Consequently, the mean and standard deviation are not necessarily calculated solely from the bin centres.
Setting an axis range or modifying histogram contents can affect how statistics are calculated.
Underflow and overflow are excluded from the accumulated statistics by default.
Histogram integral
double integral = h.Integral();
By default, the integral excludes the underflow and overflow bins when no axis range is set. To include them explicitly:
double total = h.Integral(
0,
h.GetNbinsX() + 1
);
Bin-width-weighted integral
double integral = h.Integral("width");
| Method | Meaning |
|---|---|
GetEntries() |
Histogram entry count |
Integral() |
Sum of selected bin contents |
Integral("width") |
Bin-width-weighted sum |
Weighted histograms
An observation does not necessarily contribute exactly one unit to its corresponding bin. Each observation may instead be associated with a numerical weight \(w_i\).
In ROOT, weighted filling is performed using
the second argument of Fill().
h.Fill(value, weight);
For example:
TH1D h("h", "Weighted distribution", 5, 0, 10);
h.Sumw2();
h.Fill(2.5, 0.5);
h.Fill(2.5, 1.2);
h.Fill(2.5, 2.0);
The resulting content of the corresponding bin is 3.7. However, the number of filling operations is three.
ROOT can store the sum of squared weights
using the Sumw2() method.
h.Sumw2();
Modern ROOT versions automatically enable
this storage in several situations, including
weighted filling. Nevertheless, explicitly calling Sumw2()
before filling a weighted histogram makes
the intended uncertainty treatment clear.
The uncertainty of a particular bin can be obtained using
double error = h.GetBinError(bin);
Statistical assumptions
The square-root uncertainty is based on a Poisson counting model.
Correlated observations, systematic uncertainties and more complex weighting procedures may require a different uncertainty treatment.
For very small counts, symmetric square-root errors may also be inappropriate.
Histogram normalisation
The appropriate normalisation depends on the intended physical interpretation.
Unit-sum normalisation
A histogram can be normalised so that the sum of its regular bin contents equals one.
In ROOT:
double integral = h.Integral();
if (integral > 0.0)
{
h.Scale(1.0 / integral);
}
For non-negative bin contents, each bin represents the fraction of observations or total weight within its interval.
Probability density normalisation
A histogram can also be normalised so that the area under the histogram equals one.
double integral = h.Integral();
if (integral > 0.0)
{
h.Scale(1.0 / integral, "width");
}
This operation divides the bin contents by both the total bin content and the corresponding bin widths.
Normalisation modifies the histogram
The Scale() method changes the original
histogram.
Preserve a copy if the original counts are required for subsequent calculations.
Normalising by an estimated total also introduces statistical correlations between bins that are not fully represented by individual bin errors.
Histogram operations
ROOT supports arithmetic operations between histograms.
Scaling
h.Scale(2.0);
Each bin content is multiplied by two.
Addition
h1.Add(&h2);
The corresponding bin contents of the second histogram are added to the first.
Subtraction
h1.Add(&h2, -1.0);
Multiplication
h1.Multiply(&h2);
Division
h1.Divide(&h2);
Histogram compatibility
Before performing arithmetic operations, ensure that the histograms have compatible dimensions, bin boundaries and physical interpretations.
Division also requires careful treatment of bins with zero denominator content.
ROOT's standard uncertainty propagation generally assumes independent histograms.
Efficiency calculations and correlated distributions require appropriate statistical treatment.
Rebinning
Rebinning combines neighbouring bins into larger intervals.
h.Rebin(2);
This operation combines every two adjacent bins. The bin width consequently doubles.
Rebinning can reduce statistical fluctuations, but also decreases the resolution of the distribution.
Choosing the rebinning factor
Prefer a rebinning factor that divides the original number of bins exactly.
Otherwise, remaining bins may be moved into the overflow bin.
Rebinning cannot recover information about individual observations that has already been lost through binning.
Copying a histogram
The Clone() method creates a copy of
an existing histogram.
TH1D* h_copy = static_cast<TH1D*>(
h.Clone("h_copy")
);
The copied histogram can be modified independently of the original.
h_copy->Scale(0.5);
To manage the copied histogram independently of the current ROOT directory:
h_copy->SetDirectory(nullptr);
Warning
The user is then responsible for managing its lifetime.
delete h_copy;
Alternatively, one can use smart pointers
For more information, see the chapter on ROOT files and object ownership.
Drawing histograms
Histograms can be displayed using the
Draw() method.
h.Draw();
Different drawing options control their graphical representation.
| Option | Description |
|---|---|
"HIST" |
Histogram representation |
"E" |
Statistical error bars |
"E1" |
Error bars with end caps |
"P" |
Markers |
"SAME" |
Draw on the existing pad |
For example:
h.Draw("HIST");
Customising the appearance
h.SetLineColor(kBlue);
h.SetLineWidth(2);
h.SetFillColorAlpha(kBlue, 0.25);
h.SetMarkerStyle(20);
h.SetMarkerColor(kBlue);
h.SetStats(false);
Comparing histograms
Multiple histograms can be displayed on the same canvas.
h1.SetLineColor(kBlue);
h2.SetLineColor(kRed);
h1.Draw("HIST");
h2.Draw("HIST SAME");
The first histogram establishes the displayed axes and their ranges.
Ensure that the axis range is appropriate for all displayed distributions.
More advanced graphical customisation will be discussed in the visualisation chapter.
Two-dimensional histograms
ROOT provides the TH2D class for
double-precision two-dimensional histograms.
#include <TH2D.h>
TH2D h(
"h_pt_eta",
"Momentum and pseudorapidity;p_{T} [GeV/c];#eta",
100, 0, 10,
100, -5, 5
);
Filling a two-dimensional histogram
h.Fill(pt, eta);
Weighted filling is also supported:
h.Fill(pt, eta, weight);
Accessing bin contents
double content = h.GetBinContent(
x_bin,
y_bin
);
Drawing a two-dimensional histogram
h.Draw("COLZ");
The colour represents the content of each two-dimensional bin.
Other drawing options include:
| Option | Description |
|---|---|
"COL" |
Colour representation |
"COLZ" |
Colour representation with colour scale |
"BOX" |
Boxes representing bin contents |
"LEGO" |
Three-dimensional block representation |
"SURF" |
Surface representation |
Histogram projections
A two-dimensional histogram can be projected onto either coordinate axis.
TH1D* projectionX = h.ProjectionX("h_px");
TH1D* projectionY = h.ProjectionY("h_py");
For a projection restricted to regular bins along the integrated axis:
TH1D* projectionX = h.ProjectionX(
"h_px_regular",
1,
h.GetNbinsY()
);
Mathematically, the projection onto the horizontal axis corresponds to
The projection onto the vertical axis corresponds to
Projections are useful for investigating individual distributions within a multidimensional dataset.
Choosing appropriate histogram parameters
The appearance and interpretation of a histogram depend on the selected range and bin width.
Too few bins
- Fine structures may disappear.
- Different populations may merge.
- Important physical features may be hidden.
Too many bins
- Statistical fluctuations become more visible.
- Individual bins may contain very few observations.
- The distribution may become difficult to interpret.
Inappropriate range
- Relevant observations may fall into underflow or overflow bins.
- Important structures may be compressed into a small region of the histogram.
Investigate the sensitivity to binning
Construct several histograms of the same observations using different bin widths.
Investigate whether the physical conclusions remain consistent.
A feature that disappears after a small change in binning should be interpreted carefully.
Statistical bin-width rules
Several mathematical rules can provide an initial estimate of an appropriate bin width.
Scott's rule
Freedman–Diaconis rule
where the interquartile range is
These rules provide statistical guidelines, rather than universally optimal solutions.
Detector resolution, physical scales and the purpose of the analysis should also be considered.
Complete example
The following macro generates normally distributed random observations, fills a histogram, calculates statistical quantities, draws the distribution and stores it in a ROOT file.
#include <iostream>
#include <TFile.h>
#include <TH1D.h>
#include <TRandom3.h>
#include <TCanvas.h>
void histogram_example()
{
const int n = 10000;
TH1D h(
"h_gaussian",
"Gaussian distribution;x;Counts",
100,
-5.0,
5.0
);
h.SetDirectory(nullptr);
TRandom3 random(42);
for (int i = 0; i < n; i++)
{
double x = random.Gaus(0.0, 1.0);
h.Fill(x);
}
std::cout
<< "Entries: " << h.GetEntries()
<< '\n';
std::cout
<< "Mean: " << h.GetMean()
<< '\n';
std::cout
<< "Standard deviation: "
<< h.GetStdDev()
<< '\n';
std::cout
<< "Integral: " << h.Integral()
<< '\n';
TCanvas canvas(
"canvas",
"Histogram example",
900,
600
);
h.SetLineColor(kBlue);
h.SetLineWidth(2);
h.SetFillColorAlpha(kBlue, 0.2);
h.Draw("HIST");
canvas.SaveAs("histogram.pdf");
TFile file("histogram.root", "RECREATE");
if (!file.IsZombie())
{
file.WriteObject(&h, "h_gaussian");
}
}
Execute the macro using
root -l -b -q histogram_example.C
The macro generates two output files:
histogram.pdf
histogram.root
Reproducibility
The random number generator is initialised using a fixed seed.
This allows the example to produce reproducible observations within the same implementation.
Common problems
The histogram is empty
Check whether Fill() is executed.
Verify that the observations are within the selected histogram range.
Inspect the underflow and overflow bins.
The number of entries differs from the integral
Possible reasons include:
- Weighted observations.
- Underflow and overflow entries.
- Histogram normalisation.
- Direct modification of bin contents.
The histogram contains unexpected fluctuations
The selected bin width may be too small relative to the available number of observations.
Investigate alternative binning.
The histogram disappears after closing a ROOT file
The histogram may have been owned by the closed file.
Review the object ownership section of the ROOT files chapter.
The histogram ratio contains unexpected values
Inspect the denominator histogram.
Check for zero bin contents, incompatible binning and statistical correlations.
The normalised histogram has an integral different from one
Check which normalisation was applied.
Unit-sum normalisation should be verified using
h.Integral();
Probability density normalisation should be verified using
h.Integral("width");
Exercises
Exercise 1 — Bin assignment
Construct a histogram with five bins between zero and ten.
Fill it with the following observations:
Predict the bin contents before executing your macro.
Verify your predictions using
GetBinContent().
Exercise 2 — Binning sensitivity
Generate 1000 normally distributed random observations.
Construct three histograms using 10, 30 and 100 bins.
Fill all three histograms using exactly the same observations.
Compare their appearance and discuss the effect of bin width.
Exercise 3 — Statistical quantities
Generate a normally distributed sample with mean 5 and standard deviation 2.
Calculate the mean and standard deviation independently of ROOT.
Compare your calculations with
GetMean() and GetStdDev().
Investigate the effect of changing the histogram range.
Exercise 4 — Weighted observations
Fill a histogram using observations with different weights.
Calculate the expected bin contents and uncertainties manually.
Compare your calculations with
GetBinContent() and GetBinError().
Exercise 5 — Normalisation
Generate two samples from the same probability distribution using different sample sizes.
Construct and compare their histograms.
Apply both unit-sum and probability density normalisation.
Explain the difference between the resulting vertical axes.
Exercise 6 — Two-dimensional distributions
Generate two correlated numerical variables.
Fill a two-dimensional histogram
and display it using COLZ.
Calculate the projections onto both axes.
Explain which information is lost during projection.
Exercise 7 — Experimental data
Select a physical variable from the ROOT dataset provided with your assignment.
Construct a histogram representing its distribution.
Justify your choice of:
- Histogram range.
- Number of bins.
- Axis labels and units.
- Normalisation.
- Uncertainty representation.
Interpret the resulting distribution from a physical perspective.