Kahibaro Login Register
Next
First Histogram »

First Histogram

Creating Histogram

In the first step, we create a file with the name `histogram.C and we write the following code into this file:

void histogram()
{
    TH1F *hist = new TH1F();
    hist->Draw();
}

The name of the histogram class we use is TH1F. Each letter represents one important feature:

Now we can start the program by writing root histogram.C. This will create a simple histogram with 100 bins and the limits 0 to 1 on the $x$-axis as shown in the figure below:

A first histogram.
A first histogram.

Optimizing Parameters

If we want to change the parameters of that histogram, we can add some parameters to the constructor, e.g. in the following way:

TH1F *hist = new TH1F("hist", "Histogram;X Title;Y Title", 10, -5, 5);

The first parameter is the internal name of the histogram. It is a good practice to keep it consistent with the name of the object. The second parameter is the title shown above the histogram. The next parameter is the number of bins, and the last two ones define the $x$-axis limits.

Filling the Histogram

If we want to fill a certain value into the histogram, we can use the member function Fill(double) of the TH1 class, from which TH1F inherits. For example, we can write

hist->Fill(0.5);
Optimized histogram with filled entry.
Optimized histogram with filled entry.

As we can see, this function creates a single bar at the position 0.5 with 1 as the number of entries. For testing purposes, you can add this function multiple times with other values to see what happens.

The mean and RMS values are directly calculated from the entries inside the histogram.

Fill in the only three values -2.3, 0.05, 1.7 into your histogram. What is the resulting mean value?

void histogram()
{
    TH1F *hist = new TH1F("hist", "Histogram;X Title;Y Title", 10, -5, 5);

    hist->Fill(-2.3);
    hist->Fill(0.05);
    hist->Fill(1.7);

    hist->Draw();
}

The mean value shown in the histogram is -0.55.

Random Filling

We can randomly fill the histogram for example with a Gaussian distribution using the member function FillRandom() in the following way:

hist->Fill("gaus");

It is also recommended to open a canvas manually with the class `TCanvas before drawing the histogram. The full code looks then as follows:

void histogram()
{
    TH1F *hist = new TH1F("hist", "Histogram;X Title;Y Title", 10, -5, 5);
    hist->Fill("gaus");
    TCanvas *c1 = new TCanvas();
    hist->Draw();
}
Histogram filled with random numbers using a Gaussian distribution.
Histogram filled with random numbers using a Gaussian distribution.

The mean value in this histogram is close to 0, because the standard value for a Gaussian in ROOT is 0. The standard value for $\sigma$ however is 1. The small deviations from this value are simply statistical uncertainties. By inserting more random values, the results get closer to the real values.

Next