Visualizations
Learning objectives
After completing this chapter, you should be able to:
- Understand the ROOT graphical framework.
- Create and configure canvases and pads.
- Display histograms and graphs.
- Represent statistical uncertainties.
- Customize axes, colors and graphical styles.
- Compare multiple distributions.
- Add legends and mathematical annotations.
- Create figures containing multiple panels.
- Export publication-quality scientific figures.
The ROOT graphical framework
ROOT distinguishes between scientific objects and the graphical environment in which they are displayed. For example, a histogram stores numerical information, including bin contents and statistical quantities. A canvas provides the graphical environment in which the histogram can be displayed.
flowchart TD
A["Scientific data"] --> B["ROOT objects"]
B --> C["Histograms"]
B --> D["Graphs"]
B --> E["Functions"]
C --> F["Drawing pad"]
D --> F
E --> F
F --> G["Canvas"]
G --> H["Screen"]
G --> I["PDF / SVG / PNG"]
Canvases
The TCanvas class represents the main graphical
drawing area in ROOT.
A canvas can contain histograms, graphs, functions,
text annotations and other graphical objects.
#include <TCanvas.h>
Creating a canvas
TCanvas canvas(
"canvas",
"Scientific visualization",
1000,
700
);
Constructor parameters
| Argument | Description |
|---|---|
"canvas" |
Internal object name |
"Scientific visualization" |
Window title |
1000 |
Initial width in pixels |
700 |
Initial height in pixels |
A histogram can be displayed on the canvas
using its Draw() method.
TH1D h("h", "Distribution;x;Counts", 100, -5, 5);
h.Fill(1.5);
h.Fill(2.1);
canvas.cd();
h.Draw("HIST");
The cd() method selects the canvas as the
current drawing area.
Automatic canvas creation
If no suitable drawing area exists, ROOT
can automatically create a default canvas
when Draw() is called.
However, explicitly creating a canvas provides greater control over its size, layout and graphical properties.
Pads
The TPad class represents a rectangular
drawing area within a canvas or another pad.
A canvas can contain multiple pads, allowing
several graphical objects to be displayed
independently.
The TCanvas class itself inherits from TPad.
Dividing a canvas
A canvas can be divided into equally sized
drawing areas using the Divide() method.
TCanvas canvas("canvas", "Multiple plots", 1200, 800);
canvas.Divide(2, 2);
The arguments specify the number of columns
and rows, respectively.
Pads created using Divide() are numbered
starting from one, proceeding from left to
right and from top to bottom.
canvas.cd(1);
h1.Draw();
canvas.cd(2);
h2.Draw();
canvas.cd(3);
h3.Draw();
canvas.cd(4);
h4.Draw();
Creating custom pads
The TPad constructor allows the position
and size of a drawing area to be specified
explicitly.
#include <TPad.h>
TCanvas canvas("canvas", "Custom layout", 1000, 800);
TPad* upper = new TPad(
"upper",
"Upper pad",
0.0, 0.3,
1.0, 1.0
);
TPad* lower = new TPad(
"lower",
"Lower pad",
0.0, 0.0,
1.0, 0.3
);
upper->Draw();
lower->Draw();
The four numerical arguments specify:
These coordinates are expressed relative to the parent drawing area. Both coordinate axes range from zero to one, with the origin located at the bottom-left corner.
The current drawing area
ROOT provides a global pointer named gPad,
which refers to the current drawing pad.
canvas.cd(2);
gPad->SetGrid();
gPad->SetLogy();
These operations modify the currently selected pad rather than the entire canvas.
Frequently used pad methods
| Method | Description |
|---|---|
SetGrid() |
Enable grid lines |
SetGridx() |
Enable vertical grid lines |
SetGridy() |
Enable horizontal grid lines |
SetLogx() |
Enable logarithmic x-axis |
SetLogy() |
Enable logarithmic y-axis |
SetLogz() |
Enable logarithmic z-axis |
SetLeftMargin() |
Set the left margin |
SetRightMargin() |
Set the right margin |
SetTopMargin() |
Set the upper margin |
SetBottomMargin() |
Set the lower margin |
SetTicks() |
Configure additional axis ticks |
Clear() |
Clear the drawing area |
Modified() |
Mark the pad as modified |
Update() |
Update the graphical representation |
Configuring margins
Margins are specified as fractions of the pad dimensions.
gPad->SetLeftMargin(0.13);
gPad->SetRightMargin(0.05);
gPad->SetBottomMargin(0.12);
gPad->SetTopMargin(0.08);
Appropriate margins prevent axis labels, titles and annotations from being clipped.
Drawing ROOT objects
Many ROOT objects provide a Draw() method.
h.Draw();
graph.Draw();
function.Draw();
The appearance of the object can be controlled using drawing options.
h.Draw("HIST");
Drawing options depend on the class of the displayed object.
Histogram drawing options
| Option | Description |
|---|---|
"HIST" |
Histogram representation |
"E" |
Statistical error bars |
"E1" |
Error bars with end caps |
"P" |
Markers |
"SAME" |
Overlay on the existing drawing area |
"COLZ" |
Two-dimensional color map with color scale |
"BOX" |
Two-dimensional box representation |
"LEGO" |
Three-dimensional block representation |
"SURF" |
Surface representation |
For further details on histogram construction, see the chapter on Histograms.
Overlaying objects
Multiple objects can be displayed in the same drawing area.
h1.SetLineColor(kBlue);
h2.SetLineColor(kRed);
h1.Draw("HIST");
h2.Draw("HIST SAME");
The first histogram establishes the displayed coordinate system.
The second histogram is drawn within that coordinate system.
Axis ranges
The axis range established by the first object may not be sufficient to display all subsequent objects.
Adjust the displayed range before overlaying additional distributions.
Graphs
The TGraph class represents a collection
of numerical coordinate pairs.
Consider a set of observations:
Each observation is represented by a point in a two-dimensional coordinate system.
Unlike a histogram, a graph does not group observations into bins.
Histograms versus graphs
| Histogram | Graph |
|---|---|
| Represents a distribution | Represents coordinate pairs |
| Groups observations into bins | Preserves individual coordinates |
| Stores bin contents | Stores x and y values |
Uses Fill() |
Uses SetPoint() |
| Typically represents frequencies or densities | Typically represents relationships between variables |
Creating a graph
#include <TGraph.h>
double x[] = {1, 2, 3, 4, 5};
double y[] = {2.1, 4.3, 5.8, 8.2, 10.1};
TGraph graph(5, x, y);
The constructor receives the number of points and the corresponding coordinate arrays.
Creating an empty graph
Points can also be added individually.
TGraph graph;
graph.SetPoint(0, 1.0, 2.1);
graph.SetPoint(1, 2.0, 4.3);
graph.SetPoint(2, 3.0, 5.8);
The first argument identifies the point index.
Graph indices
Unlike regular histogram bins, graph point indices start from zero.
The first point has index 0, and the
final point of a graph containing \(N\)
points has index \(N-1\).
Drawing a graph
graph.SetTitle("Measured relationship;x;y");
graph.SetMarkerStyle(20);
graph.SetMarkerSize(1.2);
graph.Draw("AP");
Graph drawing options
| Option | Description |
|---|---|
"A" |
Draw axes |
"P" |
Draw individual markers |
"L" |
Connect points using straight lines |
"C" |
Draw a smooth curve |
"B" |
Draw bars |
"AP" |
Draw axes and markers |
"AL" |
Draw axes and connecting lines |
"ALP" |
Draw axes, lines and markers |
When overlaying a graph on an existing
coordinate system, omit the "A" option.
graph1.Draw("AP");
graph2.Draw("P SAME");
Connecting observations
Connecting graph points with lines does not necessarily represent a physical relationship between them.
Lines connect points according to their stored order, not necessarily according to increasing x-coordinate.
Use connecting lines only when their interpretation is scientifically justified.
Graphs with uncertainties
ROOT provides specialized graph classes for representing these uncertainties.
Symmetric uncertainties
The TGraphErrors class represents
coordinate pairs with symmetric uncertainties.
Each point is described by
#include <TGraphErrors.h>
const int n = 5;
double x[n] = {1, 2, 3, 4, 5};
double y[n] = {2.1, 4.3, 5.8, 8.2, 10.1};
double ex[n] = {0, 0, 0, 0, 0};
double ey[n] = {0.2, 0.3, 0.4, 0.3, 0.5};
TGraphErrors graph(n, x, y, ex, ey);
graph.SetMarkerStyle(20);
graph.Draw("AP");
The arrays ex and ey contain the
horizontal and vertical uncertainties.
Individual uncertainties can also be
assigned using SetPointError().
graph.SetPoint(0, 1.0, 2.1);
graph.SetPointError(0, 0.1, 0.2);
Asymmetric uncertainties
Not all uncertainty intervals are symmetric around the measured value.
A measurement may be represented as
ROOT provides the TGraphAsymmErrors
class for this purpose.
#include <TGraphAsymmErrors.h>
TGraphAsymmErrors graph;
graph.SetPoint(0, 1.0, 2.5);
graph.SetPointError(
0,
0.1, 0.2,
0.3, 0.5
);
The arguments represent:
| Argument | Meaning |
|---|---|
0 |
Point index |
0.1 |
Lower x uncertainty |
0.2 |
Upper x uncertainty |
0.3 |
Lower y uncertainty |
0.5 |
Upper y uncertainty |
Uncertainty bands
Uncertainties can also be represented using filled graphical bands.
graph.SetFillColorAlpha(kBlue, 0.25);
graph.Draw("A3");
graph.Draw("P SAME");
The "3" drawing option represents the
area defined by the vertical error limits.
Axes
ROOT represents graphical axes using
the TAxis class.
Axis objects can be accessed through
the corresponding graphical object.
TAxis* xAxis = h.GetXaxis();
TAxis* yAxis = h.GetYaxis();
These pointers refer to existing axis objects managed by the histogram. They must not be deleted independently.
Axis titles
h.GetXaxis()->SetTitle("p_{T} [GeV/c]");
h.GetYaxis()->SetTitle("Counts");
Axis title and label sizes
h.GetXaxis()->SetTitleSize(0.045);
h.GetYaxis()->SetTitleSize(0.045);
h.GetXaxis()->SetLabelSize(0.04);
h.GetYaxis()->SetLabelSize(0.04);
Axis title offsets
h.GetXaxis()->SetTitleOffset(1.1);
h.GetYaxis()->SetTitleOffset(1.4);
Title offsets control the distance between axis titles and their corresponding axes.
Displayed histogram range
The displayed horizontal range of a
histogram can be restricted using
SetRangeUser().
h.GetXaxis()->SetRangeUser(0.0, 5.0);
The displayed vertical range can be configured using
h.SetMinimum(0.0);
h.SetMaximum(1000.0);
Display range and statistics
Restricting the displayed histogram range does not delete the excluded bins.
However, setting an axis range may affect subsequent calculations of histogram statistics and integrals.
A graphical range selection should therefore not be confused with a physical data selection.
Graph axis ranges
For graphs, the horizontal axis limits can be configured using
graph.GetXaxis()->SetLimits(0.0, 10.0);
The vertical limits can be configured using
graph.SetMinimum(0.0);
graph.SetMaximum(20.0);
Logarithmic axes
Logarithmic axes are useful when the represented quantities span several orders of magnitude.
canvas.cd();
gPad->SetLogx();
gPad->SetLogy();
Non-positive values
A logarithmic coordinate system cannot represent zero or negative values.
Ensure that the displayed axis range and relevant observations are compatible with logarithmic scaling.
Colors
ROOT provides predefined color constants.
| Constant | Color |
|---|---|
kBlack |
Black |
kWhite |
White |
kRed |
Red |
kGreen |
Green |
kBlue |
Blue |
kYellow |
Yellow |
kMagenta |
Magenta |
kCyan |
Cyan |
kOrange |
Orange |
kGray |
Gray |
These constants can be used to configure graphical properties.
h.SetLineColor(kBlue);
h.SetMarkerColor(kBlue);
h.SetFillColor(kBlue);
Variations of predefined colors can be selected using integer offsets.
h.SetLineColor(kBlue + 2);
Custom colors
Custom colors can be created using
the TColor class.
#include <TColor.h>
int color = TColor::GetColor("#4477AA");
h.SetLineColor(color);
Colors can also be specified using RGB components.
int color = TColor::GetColor(68, 119, 170);
Transparency
ROOT supports transparent graphical attributes.
h.SetFillColorAlpha(kBlue, 0.25);
The second argument specifies the opacity.
| Opacity | Interpretation |
|---|---|
0.0 |
Fully transparent |
0.5 |
Partially transparent |
1.0 |
Fully opaque |
Scientific color selection
Use colors consistently throughout an analysis.
Different physical categories should remain distinguishable without relying exclusively on color.
Combine colors with different markers and line styles when appropriate.
Line and marker styles
Graphical objects can be distinguished using different line and marker properties.
Line properties
h.SetLineColor(kBlue);
h.SetLineWidth(2);
h.SetLineStyle(1);
| Line style | Appearance |
|---|---|
1 |
Solid |
2 |
Dashed |
3 |
Dotted |
4 |
Dash-dotted |
Marker properties
graph.SetMarkerColor(kBlue);
graph.SetMarkerStyle(20);
graph.SetMarkerSize(1.2);
| Marker style | Appearance |
|---|---|
20 |
Filled circle |
21 |
Filled square |
22 |
Filled upward triangle |
23 |
Filled downward triangle |
24 |
Open circle |
25 |
Open square |
26 |
Open upward triangle |
Different marker styles are particularly useful when comparing experimental measurements.
Legends
The TLegend class identifies graphical
objects displayed within the same
drawing area.
#include <TLegend.h>
Creating a legend
TLegend legend(
0.65, 0.72,
0.90, 0.90
);
The four arguments specify the lower-left and upper-right corners of the legend using normalized device coordinates.
Adding entries
legend.AddEntry(&h1, "Experimental data", "lep");
legend.AddEntry(&h2, "Simulation", "l");
legend.Draw();
The final argument specifies the graphical representation of the corresponding entry.
| Option | Description |
|---|---|
"l" |
Line |
"p" |
Marker |
"f" |
Filled area |
"e" |
Error bar |
"lep" |
Line, error bar and marker |
Customizing a legend
legend.SetBorderSize(0);
legend.SetFillStyle(0);
legend.SetTextSize(0.035);
legend.SetHeader("Collision systems");
Passing object addresses
The AddEntry() method can receive
a pointer to an existing ROOT object.
If a histogram was created directly,
TH1D h("h", "Distribution", 100, 0, 10);
its address can be passed using
legend.AddEntry(&h, "Distribution", "l");
This does not create a new histogram.
The legend uses the existing object to determine the graphical attributes of the corresponding entry.
Mathematical notation and annotations
ROOT provides the TLatex class for
displaying text containing mathematical
notation.
#include <TLatex.h>
Adding text
TLatex text;
text.SetTextSize(0.04);
text.DrawLatex(
2.0,
100.0,
"Experimental data"
);
By default, the coordinates correspond to the physical coordinate system of the current pad.
Normalized coordinates
Annotations can also be positioned relative to the drawing area.
TLatex text;
text.SetNDC();
text.SetTextSize(0.04);
text.DrawLatex(
0.15,
0.85,
"Experimental data"
);
The annotation position is now independent of the displayed physical axis ranges.
Mathematical symbols
ROOT's TLatex syntax resembles LaTeX,
but uses the # character for many
mathematical commands.
| ROOT expression | Mathematical representation |
|---|---|
#alpha |
\(\alpha\) |
#eta |
\(\eta\) |
#phi |
\(\phi\) |
#Psi_{2} |
\(\Psi_2\) |
p_{T} |
\(p_T\) |
x^{2} |
\(x^2\) |
#sqrt{s} |
\(\sqrt{s}\) |
#frac{a}{b} |
\(\frac{a}{b}\) |
#pm |
\(\pm\) |
#Delta#phi |
\(\Delta\phi\) |
For example:
text.DrawLatex(
0.15,
0.80,
"#sqrt{s_{NN}} = 200 GeV"
);
TLatex and MathJax
ROOT's TLatex notation is not identical to conventional LaTeX notation.
Mathematical expressions written for MathJax may require modification before being used in ROOT figures.
Reference lines
The TLine class represents a straight
line between two coordinates.
#include <TLine.h>
TLine line(
0.0, 1.0,
10.0, 1.0
);
line.SetLineStyle(2);
line.SetLineWidth(2);
line.Draw();
Reference lines are useful for indicating:
- Theoretical expectations.
- Selection thresholds.
- Reference values.
- Zero crossings.
- Unity in ratio plots.
For example, a horizontal line at \(y=1\) can be used when comparing the ratio of two distributions.
Two-dimensional visualizations
Two-dimensional histograms are commonly displayed using color maps.
TH2D h(
"h",
"Joint distribution;p_{T} [GeV/c];#eta",
100, 0, 10,
100, -5, 5
);
h.Draw("COLZ");
The color of each cell represents its bin content.
Color palettes
ROOT provides several predefined color palettes.
#include <TStyle.h>
gStyle->SetPalette(kViridis);
Other available palettes include:
kBirdkRainBowkTemperatureMapkDeepSeakGrayScale
The number of contour levels can also be configured.
h.SetContour(100);
Logarithmic color scales
gPad->SetLogz();
This can be useful when the bin contents span several orders of magnitude.
Choosing a color palette
Sequential palettes are appropriate for quantities that increase from low to high values.
Diverging palettes are useful for quantities that have a meaningful central reference value, such as zero.
Avoid palettes that introduce misleading visual boundaries into smoothly varying data.
Global graphical styles
The TStyle class provides control
over ROOT's graphical defaults.
ROOT exposes the current style through
the global pointer gStyle.
#include <TStyle.h>
gStyle->SetOptStat(0);
gStyle->SetOptFit(0);
gStyle->SetTitleFont(42, "XYZ");
gStyle->SetLabelFont(42, "XYZ");
gStyle->SetTitleSize(0.045, "XYZ");
gStyle->SetLabelSize(0.04, "XYZ");
gStyle->SetPadTickX(1);
gStyle->SetPadTickY(1);
Statistics box
ROOT can display statistical information in a box within the drawing area.
gStyle->SetOptStat(0);
This disables the statistics box as a graphical default.
For an individual histogram:
h.SetStats(false);
Reusable style functions
A consistent graphical style can be defined in a separate function.
void setScientificStyle()
{
gStyle->SetOptStat(0);
gStyle->SetOptFit(0);
gStyle->SetTitleFont(42, "XYZ");
gStyle->SetLabelFont(42, "XYZ");
gStyle->SetTitleSize(0.045, "XYZ");
gStyle->SetLabelSize(0.04, "XYZ");
gStyle->SetPadLeftMargin(0.13);
gStyle->SetPadBottomMargin(0.12);
gStyle->SetPadTickX(1);
gStyle->SetPadTickY(1);
}
Call this function before creating the graphical objects.
Consistency
Define a reusable graphical style for your analysis rather than independently configuring every figure.
Consistent typography, colors and axis formatting improve the readability of scientific reports.
Drawing and object lifetime
The Draw() method generally registers
an object with the current pad.
It does not necessarily create an independent copy of that object.
Consider the following implementation:
void drawHistogram()
{
TCanvas* canvas = new TCanvas(
"canvas",
"Example",
800,
600
);
TH1D h("h", "Distribution", 100, 0, 10);
h.SetDirectory(nullptr);
h.Fill(2.5);
h.Draw();
}
The histogram is destroyed when the function terminates.
Consequently, the histogram cannot remain available in the canvas as a persistent graphical object.
Drawing a copy
Histograms provide the DrawCopy()
method.
h.DrawCopy("HIST");
This creates a copy for graphical display that is managed by the pad.
The original histogram can subsequently be destroyed without removing the displayed copy.
Updating a canvas
Changes to graphical objects may require the canvas to be updated.
h.SetLineColor(kRed);
canvas.Modified();
canvas.Update();
The Modified() method indicates
that the graphical representation
has changed.
The Update() method refreshes
the canvas.
Object ownership
The lifetime of a canvas and the lifetime of the objects displayed within it are not necessarily identical.
Always ensure that displayed objects remain valid for as long as they are required.
For further details, see the chapter on ROOT files and object ownership.
Exporting figures
ROOT supports several graphical output formats.
canvas.SaveAs("distribution.pdf");
canvas.SaveAs("distribution.png");
canvas.SaveAs("distribution.svg");
Output formats
| Format | Type | Typical application |
|---|---|---|
| Vector | Scientific publications and reports | |
| SVG | Vector | Websites and editable figures |
| PNG | Raster | Presentations and quick previews |
| JPEG | Raster | General image representation |
| ROOT | ROOT object storage | Subsequent graphical editing |
| C | C++ macro | Reconstructing a figure |
Vector and raster graphics
Vector graphics represent graphical elements using mathematical descriptions.
Raster graphics represent an image using a finite grid of pixels.
Publication-quality figures
Prefer vector formats such as PDF or SVG when preparing scientific reports.
Vector graphics generally preserve the quality of text, lines and mathematical symbols when resized.
Exporting a canvas as a ROOT object
TFile file("figures.root", "RECREATE");
file.WriteObject(&canvas, "canvas");
The stored canvas can subsequently be retrieved and modified in another ROOT session.
Multipage PDF documents
Multiple canvases can be exported into a single PDF document.
canvas1.Print("figures.pdf(");
canvas2.Print("figures.pdf");
canvas3.Print("figures.pdf)");
The opening parenthesis starts the multipage document and prints the first canvas.
The closing parenthesis prints the final canvas and closes the document.
Frequently used methods
Canvases and pads
| Method | Description |
|---|---|
Divide() |
Divide a canvas into pads |
cd() |
Select a drawing area |
SetGrid() |
Enable grid lines |
SetLogx() |
Enable logarithmic x-axis |
SetLogy() |
Enable logarithmic y-axis |
SetLogz() |
Enable logarithmic color scale |
Modified() |
Mark the drawing area as modified |
Update() |
Refresh the drawing area |
SaveAs() |
Export a figure |
Print() |
Export a figure |
Graphs
| Method | Description |
|---|---|
SetPoint() |
Assign a graph point |
SetPointError() |
Assign point uncertainties |
GetPoint() |
Retrieve point coordinates |
GetN() |
Return the number of points |
Draw() |
Display the graph |
SetTitle() |
Set graph and axis titles |
Graphical properties
| Method | Description |
|---|---|
SetLineColor() |
Set line color |
SetLineWidth() |
Set line width |
SetLineStyle() |
Set line style |
SetMarkerColor() |
Set marker color |
SetMarkerStyle() |
Set marker style |
SetMarkerSize() |
Set marker size |
SetFillColor() |
Set fill color |
SetFillColorAlpha() |
Set fill color and opacity |
Common problems
The canvas is empty
Check whether:
- The graphical object contains data.
- The
Draw()method was called. - The correct pad was selected.
- The graphical object still exists.
The second histogram replaces the first
Use the "SAME" drawing option.
h1.Draw("HIST");
h2.Draw("HIST SAME");
The axis labels are clipped
Increase the corresponding pad margin or adjust the title offset.
The histogram disappears after the macro finishes
The histogram may have been destroyed when the function terminated.
Investigate object lifetime or use
DrawCopy() when appropriate.
The logarithmic plot is incorrect
Check for zero or negative values and ensure that the displayed range is compatible with logarithmic scaling.
The graphical changes are not visible
Update the canvas:
canvas.Modified();
canvas.Update();
The exported figure has poor resolution
Prefer vector formats such as PDF or SVG.
For raster graphics, consider increasing the canvas dimensions.