Register | Login | Visitors: 183 / 24 h

First Histogram

Preparation

In order to write a root script, it is always useful to create first a file and then define a void function in that file. The name of the function and the filename should always match to easily run our scripts in the future. Hence, we create a file named "histogram.C" and define the following empty function:
void histogram()
{}
All code we present in this tutorial will be inserted into the place between the curly brackets.

Creating Histogram

For creating simple 1D histograms, the class TH1F is used. The easiest way to define a histogram is using the following line of code
 TH1F hist();
However, we prefer to create our histogram on the heap, i.e. we will have to write:
 TH1F *hist = new TH1F();
If we define our histogram without passing any arguments to the constructor, an empty histogram with 100 bins with the limits 0 and 1 is created. For most applications, this standard definition is not useful. We want to therefore create a new histogram using the following line of code:
 TH1F *hist = new TH1F("hist", "Histogram", 100, 0, 100);
The first argument has to be a string and defines the name of the histogram. It will later be displayed inside the canvas. The second argument is the title of the histogram. The third argument defines the number of bins we want to create (in this case 100). And the last two arguments are used to define the limits. For drawing the histogram, we first have to define a canvas in which the histogram will be displayed. We will do this again on the heap by writing
 TCanvas *c1 = new TCanvas();
Finally, we can draw our histogram:
 hist->Draw();
Our first empty histogram.Our first empty histogram.
As shown in the figure, histogram title is shown on top and the name is written inside the statistic box. This box contains the number of entries, in this case of course 1, the mean, and the RMS value (here denoted as standard deviation) of all entries. Our full code looks then as follows:
void histogram()
{
    TH1F *hist = new TH1F("hist", "Histogram", 100, -5, 5);
    TCanvas *c1 = new TCanvas();
    hist->Draw();
}

Filling Histogram

The drawn histogram is of course empty, but all defined parameters are shown. Now we can fill our histogram with any values we want, e.g. the number 5. In order to do that we have to write
 hist->Fill(5);
If we draw our histogram now, we can see a bar appearing at the value 5. In addition, the mean value changes now from 0 from 5. And of course, the standard deviation is still 0.
Histogram filled with one entry.Histogram filled with one entry.
The full code looks as follows:
void histogram()
{
    TH1F *hist = new TH1F("hist", "Histogram", 100, -5, 5);
    TCanvas *c1 = new TCanvas();
    hist->Fill(5);
    hist->Draw();
}
In the next step, you can fill more values to the histogram to find out what will happen.
This page contains 608 words and 3670 characters.