19.2. ROOT Objects in Python
Table of Contents
Histograms
In PyROOT, histogram classes such as TH1F, TH1D, TH2F, and others are exactly the same C++ classes you use in the ROOT C++ interface. The difference is only in how you create and manipulate them from Python syntax.
You first need to import ROOT in Python, usually as:
import ROOTTo create a simple one dimensional float histogram with 100 bins between 0 and 10, you write:
h = ROOT.TH1F("h", "Example histogram;X axis;Entries", 100, 0.0, 10.0)The arguments are the same as in C++: internal name, title, number of bins, lower edge, upper edge. Axis titles are separated by semicolons in the string.
Filling a histogram uses the same Fill method:
h.Fill(3.2)
h.Fill(7.5, 2.0) # with weight 2.0You can also fill histograms inside Python loops. For example, if you want to fill a histogram with random Gaussian numbers using ROOT’s random generator:
rand = ROOT.TRandom3(0) # seed
for _ in range(100000):
value = rand.Gaus(0.0, 1.0)
h.Fill(value)You can access basic properties with the familiar methods:
entries = h.GetEntries()
mean = h.GetMean()
rms = h.GetRMS()These methods return Python float or int values through the automatic C++ to Python conversion.
To draw the histogram you can call:
c = ROOT.TCanvas("c", "c", 800, 600)
h.Draw()
c.Update()
If you work in a Python shell that understands GUI event loops (for example python -i with ROOT graphics enabled), the canvas window will appear as in C++. In a Jupyter notebook, you often need to use the built in display integration:
%jsroot on
h.Draw()and the current canvas is shown inline.
You can change histogram style from Python using the same methods: for instance
h.SetLineColor(ROOT.kRed)
h.SetLineWidth(2)
h.SetFillColor(ROOT.kBlue - 10)
The constant color names, such as kRed, are available in the ROOT module.
Saving histograms to ROOT files is also identical to C++:
f = ROOT.TFile("histos.root", "RECREATE")
h.Write()
f.Close()
When you read them back, you use TFile.Get which returns a ROOT object that behaves as a histogram in Python:
f = ROOT.TFile("histos.root")
h2 = f.Get("h")
h2.Draw()One important practical detail in PyROOT is object lifetime. If you create a histogram in a function and do not keep a Python reference to it, it may be destroyed by Python’s garbage collector, which can lead to confusion when drawing. A simple pattern is to keep histograms in a Python list or dictionary that lives long enough:
histos = []
def make_histo(name):
h = ROOT.TH1F(name, name, 50, 0.0, 5.0)
histos.append(h)
return hThis way, the histogram objects remain valid while you use them.
Always keep a Python reference to histograms that you plan to draw or save. If the last Python reference disappears, the object can be deleted even if a canvas still shows it.
Graphs
TGraph and its variants can also be used from Python without special wrapping code. All the C++ constructors and methods are available through the ROOT module.
The simplest way to create a TGraph from Python lists or arrays is to use ROOT’s constructor that accepts the number of points and C-style arrays. PyROOT automatically converts many Python containers into the required form. For example:
import array
import ROOT
x_vals = array.array("d", [0.0, 1.0, 2.0, 3.0])
y_vals = array.array("d", [0.1, 0.9, 2.2, 3.1])
g = ROOT.TGraph(len(x_vals), x_vals, y_vals)
g.SetTitle("Simple graph;X;Y")
Here the array module from the Python standard library provides a C-style array of doubles ("d"). For TGraph and TGraphErrors this is a reliable way to pass data.
If you already use NumPy in your Python analysis, you can also pass NumPy arrays in many cases, because PyROOT can interpret them as the required pointer types:
import numpy as np
x_vals = np.linspace(0, 3, 4, dtype="float64")
y_vals = np.array([0.1, 0.9, 2.2, 3.1], dtype="float64")
g = ROOT.TGraph(len(x_vals), x_vals, y_vals)Once the graph exists, you style it and draw it:
g.SetMarkerStyle(20)
g.SetMarkerColor(ROOT.kBlue)
g.SetLineColor(ROOT.kBlue)
g.Draw("AP") # Axes + Points
For graphs with errors, you can use TGraphErrors or TGraphAsymmErrors. The pattern is similar, but you provide error arrays in addition to x and y:
ex = array.array("d", [0.0, 0.0, 0.0, 0.0])
ey = array.array("d", [0.05, 0.08, 0.10, 0.07])
ge = ROOT.TGraphErrors(len(x_vals), x_vals, y_vals, ex, ey)
ge.SetTitle("Measurements with errors;X;Y")
ge.SetMarkerStyle(21)
ge.Draw("AP")When you read graphs from ROOT files in Python, the returned objects behave exactly as in C++:
f = ROOT.TFile("graphs.root")
g2 = f.Get("mygraph")
g2.Draw("AL")
You can combine several graphs into a TMultiGraph in Python, just as in C++:
mg = ROOT.TMultiGraph()
mg.Add(g)
mg.Add(ge)
mg.Draw("AP")
mg.GetXaxis().SetTitle("X")
mg.GetYaxis().SetTitle("Y")
As with histograms, keep Python references to graphs you want to keep. If you construct small arrays inside a function and pass them into TGraph, they should outlive the graph construction, but you usually do not need to keep explicit references to the arrays after that, because the graph copies the data internally. However, you still need to keep a reference to the graph object itself.
Keep a Python reference to graphs you need to draw or modify later. A graph without a live Python variable can be deleted by the garbage collector, which may lead to missing plots or crashes.
Canvases
TCanvas is the main drawing surface in ROOT and you use it from Python in the same way as in C++. Creating a canvas is straightforward:
import ROOT
c1 = ROOT.TCanvas("c1", "My canvas", 800, 600)You can then draw histograms and graphs on this canvas:
h.Draw()
c1.Update()In an interactive Python session, the canvas window appears and behaves exactly like in the C++ ROOT session. You can divide the canvas into pads from Python:
c1.Divide(2, 2)
c1.cd(1)
h.Draw()
c1.cd(2)
g.Draw("AP")
Each pad is selected with cd before drawing. This works identically in PyROOT.
You can also set canvas properties from Python. For example:
c1.SetGrid()
c1.SetLogy()Saving canvases to files is especially convenient in Python scripts:
c1.SaveAs("plot.png")
c1.SaveAs("plot.pdf")
If you work in Jupyter notebooks, ROOT integrates with the notebook display. With %jsroot on activated, each call to Draw shows the current canvas inline. Sometimes you will want to explicitly show the current canvas:
from ROOT import gPad
gPad.Update()In batch scripts that run without a graphical display, you can tell ROOT not to open any windows:
ROOT.gROOT.SetBatch(True)
c1 = ROOT.TCanvas("c1", "c1", 800, 600)
h.Draw()
c1.SaveAs("hist.png")In this mode, the canvas still exists and can be saved to files, but no window is shown.
Management of canvas lifetimes is again important in PyROOT. If the last Python variable that refers to a canvas is removed, the canvas can be destroyed, which may close the window unexpectedly. Usually you keep a canvas variable at module scope or inside a controlling object so that it survives as long as needed.
Finally, you can connect Python logic with GUI actions by using ROOT’s event loop functions. For quick analysis it is more common to use PyROOT in a script-like style, but the full graphical capabilities remain available.
When scripting with PyROOT, set ROOT.gROOT.SetBatch(True) if you run on a server or in a non graphical environment. Otherwise ROOT may try to open windows and your job can hang or crash.
Views: 0
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
-
Comments
Please login to add a comment.
Don't have an account? Register now!