Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
hist000_TH1_first.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_hist
3## Hello World example for TH1
4##
5## Shows how to create, fill and write a histogram to a ROOT file.
6##
7## \macro_code
8## \macro_output
9##
10## \date November 2024
11## \author Giacomo Parolini (CERN)
12
13import ROOT
14
15# Open the file to write the histogram to
16with ROOT.TFile.Open("outfile.root", "RECREATE") as outFile:
17 # Create the histogram object
18 # There are several constructors you can use (see TH1). In this example we use the
19 # simplest one, accepting a number of bins and a range.
20 histogram = ROOT.TH1D("histogram", "My first ROOT histogram", nbinsx = 30, xlow = 0.0, xup = 10.0)
21
22 # Fill the histogram. In this simple example we use a fake set of data.
23 # The 'D' in TH1D stands for 'double', so we fill the histogram with doubles.
24 # In general you should prefer TH1D over TH1F unless you have a very specific reason
25 # to do otherwise.
26 values = [1, 2, 3, 3, 3, 4, 3, 2, 1, 0]
27 for val in values:
28 histogram.Fill(val)
29
30 # Write the histogram to `outFile`.
31 outFile.WriteObject(histogram, histogram.GetName())
32
33 # When `with` block exits, `outFile` will close itself and write its contents to disk.