KAHIBARO Bookshelves
Discord Login Register

18.5. Creating Histograms

Table of Contents

`Histo1D()`

When using RDataFrame, histograms are not created by calling the TH1 constructor directly. Instead, you ask the dataframe to produce histograms from its columns. The method Histo1D() is the standard way to create one dimensional histograms from a column or an expression.

A minimal example starts from a dataframe, typically built from a TTree:

cpp
ROOT::RDataFrame df("tree", "file.root");
auto h_pt = df.Histo1D("pt");

Here "pt" is the name of a column in the dataframe, often corresponding to a TTree branch. The result h_pt is an RResultPtr to a TH1 object. It behaves like a smart pointer and the actual histogram is only filled when needed, for example when you draw it or access its contents.

You can also specify the histogram model explicitly. This controls the number of bins, axis range, and optionally the title:

cpp
ROOT::RDataFrame df("tree", "file.root");
// Explicit binning: 100 bins from 0 to 200
auto h_pt = df.Histo1D(
    {"h_pt", "Transverse momentum; p_{T} [GeV]; Events", 100, 0.0, 200.0},
    "pt"
);

The first argument here is a ROOT::RDF::TH1DModel or similar, constructed implicitly from the initializer list. The second argument is the column or expression to be filled. The histogram name "h_pt" is used when saving to a ROOT file, and the title sets both the main title and axis titles through the usual ROOT semicolon convention.

You can also fill from an expression instead of a simple column name. RDataFrame expressions are given as strings in C++ syntax and can combine existing columns:

cpp
auto h_mass = df.Define("m2", "E*E - px*px - py*py - pz*pz")
                .Histo1D({"h_m2", "Invariant mass squared; m^{2}; Events", 80, -1.0, 3.0},
                         "m2");

Here Define creates a new column "m2" which is then used by Histo1D(). The key point is that Histo1D() always takes a single value per event, either directly from a column or from a defined expression.

Often you want to account for per event weights. For that there is a second parameter to Histo1D() that specifies the weight column:

cpp
auto h_weighted = df.Histo1D(
    {"h_weighted", "Weighted distribution; x; Weighted events", 50, 0.0, 5.0},
    "x",
    "weight"
);

In this case, every entry contributes to the histogram with a weight given by the value of the "weight" column. Both value and weight columns must be of compatible numeric types.

The interaction with lazy evaluation is important. Calling Histo1D() does not immediately loop over all entries. The loop runs only when the result is accessed. For example:

cpp
auto h = df.Histo1D("pt");
h->Draw();            // triggers the event loop and fills the histogram

After the draw call, the histogram is materialized and you can query its properties or save it:

cpp
std::cout << "Entries: " << h->GetEntries() << "\n";
TFile out("histos.root", "RECREATE");
h->Write();

Because RDataFrame supports multiple independent actions in one pass over the data, you can ask for several histograms and benefit from a single event loop:

cpp
auto h_pt  = df.Histo1D({"h_pt",  "p_{T}", 100, 0, 200}, "pt");
auto h_eta = df.Histo1D({"h_eta", "#eta",  60, -3, 3},   "eta");
// First access to any result triggers filling of both
h_pt->Draw();

The binning choices follow the same principles as for standard TH1 objects. Very fine binning on large datasets increases memory usage and reduces statistical power per bin, while too coarse binning hides structure in the data. Use the knowledge of your variables and number of entries to choose appropriate binning.

If you later need to normalize or scale the histogram, you do it on the resulting TH1, not through Histo1D():

cpp
auto h = df.Histo1D({"h_x", "x; x; Normalized events", 50, 0, 10}, "x");
h->Scale(1.0 / h->Integral());   // unit normalization

Remember that Histo1D() creates a histogram as a lazy action. The underlying data loop runs only when you first access the histogram result, for example via Draw(), Write(), or numerical queries. This makes it efficient to define many histograms and other actions that are executed together in a single pass over the data.

`Histo2D()`

For two dimensional histograms, RDataFrame provides Histo2D(). Instead of a single value per event, you now provide a pair of values, one for the X axis and one for the Y axis. As with Histo1D(), you work with column names or expressions, and the method returns an RResultPtr to a TH2 object.

A simple example uses two existing columns, for example "pt" and "eta":

cpp
ROOT::RDataFrame df("tree", "file.root");
auto h2_pt_eta = df.Histo2D("pt", "eta");

In this simplest form, ROOT uses default binning based on the column types, which is rarely what you want for real analyses. Explicit binning is normally preferable:

cpp
auto h2_pt_eta = df.Histo2D(
    {"h2_pt_eta",
     "p_{T} vs #eta; p_{T} [GeV]; #eta; Events",
     100, 0.0, 200.0,    // X axis: pt
     60, -3.0, 3.0},     // Y axis: eta
    "pt",
    "eta"
);

The first argument is a TH2 model which defines the histogram name, title, number of bins, and ranges in both dimensions. The second and third arguments are the X and Y value sources. As for 1D histograms, these can be either simple column names or more complex expressions.

For expressions, you can use the same Define mechanism to build derived quantities before histogramming:

cpp
auto df2 = df.Define("pt_over_mass", "pt / mass")
             .Define("logE", "log(E)");
auto h2 = df2.Histo2D(
    {"h2_ptoM_logE",
     "p_{T}/m vs log(E); p_{T}/m; log(E); Events",
     80, 0.0, 8.0,
     80, 0.0, 10.0},
    "pt_over_mass",
    "logE"
);

If each event has an associated weight, you can pass a weight column as a third data argument:

cpp
auto h2_weighted = df.Histo2D(
    {"h2_xy_w",
     "Weighted 2D distribution; x; y; Weighted events",
     50, 0.0, 5.0,
     50, -2.0, 2.0},
    "x",
    "y",
    "weight"
);

Here each event contributes weight to the bin that corresponds to (x, y). The behavior is analogous to Histo1D() with weights.

The same lazy evaluation rules apply. Defining Histo2D() does not immediately loop over the dataset. The loop happens on first use of any result:

cpp
auto h2 = df.Histo2D({"h2", "X vs Y; X; Y; Events", 40, 0, 10, 40, -5, 5},
                     "X", "Y");
// Trigger event loop by drawing the histogram
TCanvas c("c", "c", 800, 600);
h2->Draw("COLZ");
c.SaveAs("xy_distribution.png");

After this, the TH2 is fully filled and can be further manipulated or saved to a file.

Binning and axis ranges in two dimensions require particular attention. Too narrow a range along one axis may cut away events of interest or move many entries into underflow and overflow bins, which can distort the visual impression. Conversely, a range that is too wide can waste bins on empty regions. It is often useful to build a quick coarse histogram with generous ranges to explore the variable space, then refine the binning for the final analysis.

As with 1D histograms, multiple 2D histograms and other actions can be defined on the same dataframe. RDataFrame then processes all of them in a single pass, which is particularly beneficial for large datasets:

cpp
auto h2_pt_eta   = df.Histo2D({"h2_pt_eta",   "", 80, 0, 200, 60, -3, 3},   "pt",   "eta");
auto h2_pt_phi   = df.Histo2D({"h2_pt_phi",   "", 80, 0, 200, 64, -3.2, 3.2}, "pt", "phi");
auto h2_eta_phi  = df.Histo2D({"h2_eta_phi",  "", 60, -3, 3, 64, -3.2, 3.2}, "eta","phi");
// Accessing any of the histograms triggers a single event loop producing all three
h2_pt_eta->Draw("COLZ");

Once created, 2D histograms obtained from Histo2D() behave like standard TH2 objects. You can compute projections, profiles, or perform fits using the regular ROOT tools that operate on histograms.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Introduction to ROOT
    • ☰ 1.1. What Is ROOT?
      • ☰ 1.2. Installing ROOT
        • ☰ 1.3. Starting ROOT
          • ☰ 1.4. Your First ROOT Session
          • ☰ 2. C++ Basics for ROOT
            • ☰ 2.1. Why ROOT Uses C++
              • ☰ 2.2. Variables and Data Types
                • ☰ 2.3. Operators
                  • ☰ 2.4. Conditional Statements
                    • ☰ 2.5. Loops
                      • ☰ 2.6. Functions
                        • ☰ 2.7. Arrays and Vectors
                        • ☰ 3. ROOT Macros
                          • ☰ 3.1. What Is a ROOT Macro?
                            • ☰ 3.2. Running ROOT Macros
                              • ☰ 3.3. Functions Inside ROOT Macros
                                • ☰ 3.4. Compiling ROOT Macros
                                  • ☰ 3.5. Organizing a ROOT Project
                                  • ☰ 4. ROOT Objects and the ROOT Object Model
                                    • ☰ 4.1. Introduction to ROOT Classes
                                      • ☰ 4.2. Object Names and Titles
                                        • ☰ 4.3. ROOT Collections
                                          • ☰ 4.4. Inspecting ROOT Objects
                                          • ☰ 5. Histograms
                                            • ☰ 5.1. Introduction to Histograms
                                              • ☰ 5.2. Creating a 1D Histogram
                                                • ☰ 5.3. Filling Histograms
                                                  • ☰ 5.4. Drawing Histograms
                                                    • ☰ 5.5. Histogram Properties
                                                      • ☰ 5.6. Accessing Histogram Bins
                                                        • ☰ 5.7. Histogram Errors
                                                          • ☰ 5.8. Normalizing Histograms
                                                            • ☰ 5.9. Combining Histograms
                                                            • ☰ 6. Two-Dimensional Histograms
                                                              • ☰ 6.1. Creating 2D Histograms
                                                                • ☰ 6.2. Filling 2D Histograms
                                                                  • ☰ 6.3. Drawing 2D Histograms
                                                                    • ☰ 6.4. Projections
                                                                      • ☰ 6.5. Profiles
                                                                      • ☰ 7. Graphs
                                                                        • ☰ 7.1. Introduction to TGraph
                                                                          • ☰ 7.2. Creating a TGraph
                                                                            • ☰ 7.3. Graph Styling
                                                                              • ☰ 7.4. TGraphErrors
                                                                                • ☰ 7.5. TGraphAsymmErrors
                                                                                  • ☰ 7.6. MultiGraph
                                                                                  • ☰ 8. Canvases and Plotting
                                                                                    • ☰ 8.1. TCanvas
                                                                                      • ☰ 8.2. Dividing a Canvas
                                                                                        • ☰ 8.3. Drawing Multiple Objects
                                                                                          • ☰ 8.4. Legends
                                                                                            • ☰ 8.5. Text and Annotations
                                                                                              • ☰ 8.6. Logarithmic Axes
                                                                                                • ☰ 8.7. Saving Plots
                                                                                                • ☰ 9. Styling ROOT Plots
                                                                                                  • ☰ 9.1. ROOT Plot Styles
                                                                                                    • ☰ 9.2. Axis Configuration
                                                                                                      • ☰ 9.3. Line Styles
                                                                                                        • ☰ 9.4. Marker Styles
                                                                                                          • ☰ 9.5. Publication-Quality Figures
                                                                                                          • ☰ 10. Mathematical Functions
                                                                                                            • ☰ 10.1. Introduction to TF1
                                                                                                              • ☰ 10.2. Built-in Functions
                                                                                                                • ☰ 10.3. Custom Functions
                                                                                                                  • ☰ 10.4. Evaluating Functions
                                                                                                                    • ☰ 10.5. Function Integrals
                                                                                                                    • ☰ 11. Curve Fitting
                                                                                                                      • ☰ 11.1. Introduction to Fitting
                                                                                                                        • ☰ 11.2. Gaussian Fits
                                                                                                                          • ☰ 11.3. Polynomial Fits
                                                                                                                            • ☰ 11.4. Custom Fit Functions
                                                                                                                              • ☰ 11.5. Fit Parameters
                                                                                                                                • ☰ 11.6. Goodness of Fit
                                                                                                                                  • ☰ 11.7. Fit Residuals
                                                                                                                                    • ☰ 11.8. Fitting Graphs
                                                                                                                                    • ☰ 12. ROOT Files
                                                                                                                                      • ☰ 12.1. Introduction to ROOT Files
                                                                                                                                        • ☰ 12.2. Creating ROOT Files
                                                                                                                                          • ☰ 12.3. Writing Objects
                                                                                                                                            • ☰ 12.4. Reading ROOT Files
                                                                                                                                              • ☰ 12.5. Exploring ROOT Files
                                                                                                                                                • ☰ 12.6. Directories Inside ROOT Files
                                                                                                                                                • ☰ 13. TTrees
                                                                                                                                                  • ☰ 13.1. Introduction to TTrees
                                                                                                                                                    • ☰ 13.2. Creating a TTree
                                                                                                                                                      • ☰ 13.3. Filling a TTree
                                                                                                                                                        • ☰ 13.4. Writing a TTree to a File
                                                                                                                                                          • ☰ 13.5. Reading a TTree
                                                                                                                                                            • ☰ 13.6. Inspecting TTrees
                                                                                                                                                              • ☰ 13.7. Drawing Data from TTrees
                                                                                                                                                                • ☰ 13.8. Applying Selection Cuts
                                                                                                                                                                  • ☰ 13.9. Branch Addresses
                                                                                                                                                                  • ☰ 14. Event-Based Data Analysis
                                                                                                                                                                    • ☰ 14.1. Understanding Event Data
                                                                                                                                                                      • ☰ 14.2. Event Loops
                                                                                                                                                                        • ☰ 14.3. Event Selection
                                                                                                                                                                          • ☰ 14.4. Derived Quantities
                                                                                                                                                                            • ☰ 14.5. Analysis Workflow
                                                                                                                                                                            • ☰ 15. Working with Real Experimental Data
                                                                                                                                                                              • ☰ 15.1. Importing Text Data
                                                                                                                                                                                • ☰ 15.2. Converting Data to ROOT
                                                                                                                                                                                  • ☰ 15.3. Data Cleaning
                                                                                                                                                                                    • ☰ 15.4. Data Calibration
                                                                                                                                                                                      • ☰ 15.5. Signal and Background
                                                                                                                                                                                      • ☰ 16. Random Numbers and Simulations
                                                                                                                                                                                        • ☰ 16.1. Random Number Generation
                                                                                                                                                                                          • ☰ 16.2. Common Distributions
                                                                                                                                                                                            • ☰ 16.3. Simple Monte Carlo Simulation
                                                                                                                                                                                              • ☰ 16.4. Detector Resolution Simulation
                                                                                                                                                                                                • ☰ 16.5. Efficiency Simulation
                                                                                                                                                                                                • ☰ 17. Statistical Analysis with ROOT
                                                                                                                                                                                                  • ☰ 17.1. Basic Statistics
                                                                                                                                                                                                    • ☰ 17.2. Probability Distributions
                                                                                                                                                                                                      • ☰ 17.3. Statistical Uncertainties
                                                                                                                                                                                                        • ☰ 17.4. Chi-Square Tests
                                                                                                                                                                                                          • ☰ 17.5. Confidence Intervals
                                                                                                                                                                                                          • ☰ 18. Modern ROOT with RDataFrame
                                                                                                                                                                                                            • ☰ 18.1. Introduction to RDataFrame
                                                                                                                                                                                                              • ☰ 18.2. Loading Data
                                                                                                                                                                                                                • ☰ 18.3. Filtering Data
                                                                                                                                                                                                                  • ☰ 18.4. Defining New Columns
                                                                                                                                                                                                                    • ☰ 18.5. Creating Histograms
                                                                                                                                                                                                                      • ☰ 18.6. Statistical Operations
                                                                                                                                                                                                                        • ☰ 18.7. Saving Results
                                                                                                                                                                                                                          • ☰ 18.8. Multithreading
                                                                                                                                                                                                                          • ☰ 19. ROOT and Python
                                                                                                                                                                                                                            • ☰ 19.1. Introduction to PyROOT
                                                                                                                                                                                                                              • ☰ 19.2. ROOT Objects in Python
                                                                                                                                                                                                                                • ☰ 19.3. Reading ROOT Files with Python
                                                                                                                                                                                                                                  • ☰ 19.4. PyROOT and NumPy
                                                                                                                                                                                                                                    • ☰ 19.5. PyROOT and Matplotlib
                                                                                                                                                                                                                                      • ☰ 19.6. Choosing Between C++ and Python
                                                                                                                                                                                                                                      • ☰ 20. Advanced TTree Techniques
                                                                                                                                                                                                                                        • ☰ 20.1. Trees with Multiple Branches
                                                                                                                                                                                                                                          • ☰ 20.2. Storing std::vector Objects
                                                                                                                                                                                                                                            • ☰ 20.3. TChain
                                                                                                                                                                                                                                              • ☰ 20.4. Friends
                                                                                                                                                                                                                                                • ☰ 20.5. Efficient TTree Analysis
                                                                                                                                                                                                                                                • ☰ 21. ROOT for Particle and Nuclear Physics
                                                                                                                                                                                                                                                  • ☰ 21.1. Four-Vectors
                                                                                                                                                                                                                                                    • ☰ 21.2. Particle Kinematics
                                                                                                                                                                                                                                                      • ☰ 21.3. Invariant Mass
                                                                                                                                                                                                                                                        • ☰ 21.4. Angular Distributions
                                                                                                                                                                                                                                                          • ☰ 21.5. Detector Spectra
                                                                                                                                                                                                                                                          • ☰ 22. Debugging and Common ROOT Problems
                                                                                                                                                                                                                                                            • ☰ 22.1. ROOT Object Ownership
                                                                                                                                                                                                                                                              • ☰ 22.2. Null Pointers
                                                                                                                                                                                                                                                                • ☰ 22.3. Segmentation Faults
                                                                                                                                                                                                                                                                  • ☰ 22.4. Missing Histograms
                                                                                                                                                                                                                                                                    • ☰ 22.5. ROOT File Problems
                                                                                                                                                                                                                                                                      • ☰ 22.6. TTree Branch Problems
                                                                                                                                                                                                                                                                        • ☰ 22.7. Histogram Range Problems
                                                                                                                                                                                                                                                                          • ☰ 22.8. Fit Failures
                                                                                                                                                                                                                                                                            • ☰ 22.9. Debugging ROOT Macros
                                                                                                                                                                                                                                                                            • ☰ 23. Writing Better ROOT Analysis Code
                                                                                                                                                                                                                                                                              • ☰ 23.1. Separating Analysis and Plotting
                                                                                                                                                                                                                                                                                • ☰ 23.2. Using Functions
                                                                                                                                                                                                                                                                                  • ☰ 23.3. Using Header Files
                                                                                                                                                                                                                                                                                    • ☰ 23.4. Naming Conventions
                                                                                                                                                                                                                                                                                      • ☰ 23.5. Avoiding Hard-Coded Values
                                                                                                                                                                                                                                                                                        • ☰ 23.6. Configuration Parameters
                                                                                                                                                                                                                                                                                          • ☰ 23.7. Reproducible Analysis
                                                                                                                                                                                                                                                                                            • ☰ 23.8. Version Control with Git
                                                                                                                                                                                                                                                                                            • ☰ 24. Final Project
                                                                                                                                                                                                                                                                                              • ☰ 24.1. Project Overview
                                                                                                                                                                                                                                                                                                • ☰ 24.2. Analyze a complete scientific dataset using ROOT.
                                                                                                                                                                                                                                                                                                  • ☰ 24.3. Import the Data
                                                                                                                                                                                                                                                                                                    • ☰ 24.4. Explore the Dataset
                                                                                                                                                                                                                                                                                                      • ☰ 24.5. Apply Data Selection
                                                                                                                                                                                                                                                                                                        • ☰ 24.6. Create Histograms
                                                                                                                                                                                                                                                                                                          • ☰ 24.7. Fit the Data
                                                                                                                                                                                                                                                                                                            • ☰ 24.8. Calculate Physical Quantities
                                                                                                                                                                                                                                                                                                              • ☰ 24.9. Estimate Statistical Uncertainties
                                                                                                                                                                                                                                                                                                                • ☰ 24.10. Create Publication-Quality Figures
                                                                                                                                                                                                                                                                                                                  • ☰ 24.11. Save the Analysis Results
                                                                                                                                                                                                                                                                                                                    • ☰ 24.12. Write a Short Analysis Report
                                                                                                                                                                                                                                                                                                                    • ☰ 25. Appendices
                                                                                                                                                                                                                                                                                                                      • ☰ 25.1. A. ROOT Command Cheat Sheet
                                                                                                                                                                                                                                                                                                                        • ☰ 25.2. B. ROOT Histogram Classes
                                                                                                                                                                                                                                                                                                                          • ☰ 25.3. C. ROOT Graph Classes
                                                                                                                                                                                                                                                                                                                            • ☰ 25.4. D. Common TTree Commands
                                                                                                                                                                                                                                                                                                                              • ☰ 25.5. E. Common Drawing Options
                                                                                                                                                                                                                                                                                                                                • ☰ 25.6. F. Common Fit Functions
                                                                                                                                                                                                                                                                                                                                  • ☰ 25.7. G. ROOT C++ Cheat Sheet
                                                                                                                                                                                                                                                                                                                                    • ☰ 25.8. H. PyROOT Cheat Sheet
                                                                                                                                                                                                                                                                                                                                      • ☰ 25.9. I. Common ROOT Errors and Solutions
                                                                                                                                                                                                                                                                                                                                        • ☰ 25.10. J. Recommended ROOT Analysis Workflow