Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
_tgraph.pyzdoc
Go to the documentation of this file.
1\pythondoc TGraph
2
3The `TGraph` class in PyROOT is a versatile tool for creating and visualizing 2D graphs with points connected by straight lines. It is commonly used for plotting scatter plots, line graphs, and interpolated data visualizations.
4
5### Key Features:
61. **Create and manipulate 2D graphs** with dynamic data points.
72. **Customize graph appearance:** markers, lines, colors, and more.
83. **Add labels, legends, and multiple datasets** for comprehensive visualization.
94. **Save graphs** in formats like .png, .pdf, and .root.
10
11Below are two examples:
121. **Basic Example:** Demonstrating TGraph functionalities.
132. **Advanced Example:** Visualizing and comparing multiple datasets.
14
15## Basic Example Usage
16
17\code{.py}
18import ROOT
19import numpy as np
20
21# Create a canvas to draw the graph
22canvas = ROOT.TCanvas("c1", "TGraph Example", 800, 600)
23
24# Define the number of data points
25n = 10
26# Generate X values as a sequence from 0 to 9
27x = numpy.linspace(0, 9, n)
28# Compute Y values as the square of X values
29y = x**2
30
31# Create a TGraph object using the defined X and Y values
32graph = ROOT.TGraph(n, x, y)
33
34# Get the current number of points in the graph
35n = graph.GetN()
36# Add a new point to the graph at the specified index
37graph.SetPoint(n, 10, 100)
38
39# Retrieve the coordinates of the 3rd point (index 2)
40x_val = graph.GetPointX(2)
41y_val = graph.GetPointY(2)
42print(f"Point {2}: ({x_val}, {y_val})")
43
44# Customize graph appearance
45graph.SetTitle("Example Graph;X-axis Title;Y-axis Title")
46graph.SetMarkerStyle(21)
47graph.SetMarkerSize(2)
48graph.SetMarkerColor(4)
49graph.SetLineColor(2)
50graph.SetLineStyle(1)
51graph.SetLineWidth(2)
52
53# Draw the graph with axes ("A"), lines ("L"), and points ("P")
54graph.Draw("ALP")
55
56# Save the graph as a PNG file
57canvas.SaveAs("tgraph_example.png")
58\endcode
59
60## Advanced Example: Comparing Two Datasets
61This example demonstrates how to visualize and compare multiple datasets using `TGraph`. The script customizes axes, labels and legends. The output is a comparative graph saved as a PDF.
62
63\code{.py}
64import ROOT
65import numpy
66
67# Define benchmark data for Dataset 1 using NumPy arrays
68dataset1_x_values = numpy.array([32, 64, 128, 256, 512, 1024, 2048], dtype=float)
69dataset1_y_values = numpy.array([2, 3, 7, 13, 26, 48, 100], dtype=float)
70
71# Define benchmark data for Dataset 2 using NumPy arrays
72dataset2_x_values = numpy.array([32, 64, 128, 256, 512, 1024, 2048], dtype=float)
73dataset2_y_values = numpy.array([2, 3, 7, 13, 26, 47, 92], dtype=float)
74
75# Create TGraph objects for Dataset 1 and Dataset 2
76graph1 = ROOT.TGraph(len(dataset1_x_values), dataset1_x_values, dataset1_y_values)
77graph2 = ROOT.TGraph(len(dataset2_x_values), dataset2_x_values, dataset2_y_values)
78
79# Configure canvas dimensions for displaying the comparative plot
80width, height = 1920, 1080
81canvas = ROOT.TCanvas("c", "Datasets Comparison", width, height)
82# Left, Right, Bottom, Top margins
83canvas.SetMargin(0.08, 0.05, 0.15, 0.09)
84
85# Retrieve y-axis minimum and maximum values to set dynamic axis ranges for the plot
86ymin = graph1.GetHistogram().GetMinimum()
87ymax = graph1.GetHistogram().GetMaximum()
88
89# Configure graph1
90graph1.SetTitle("TGraph dataset comparison plot title")
91graph1.GetXaxis().SetTitle("X Axis Title")
92graph1.GetXaxis().SetTitleSize(0.04)
93graph1.GetXaxis().SetTitleOffset(1.3)
94graph1.GetXaxis().SetLabelSize(0.03)
95
96# Hide default x-axis labels and ticks to customize axis appearance
97graph1.GetXaxis().SetLabelSize(0)
98graph1.GetXaxis().SetTickLength(0)
99
100graph1.GetYaxis().SetTitle("Y Axis Title")
101graph1.GetYaxis().SetTitleSize(0.04)
102graph1.GetYaxis().SetTitleOffset(0.7)
103graph1.GetYaxis().SetLabelSize(0.03)
104# Ensure y-axis includes zero
105graph1.GetYaxis().SetRangeUser(0, ymax)
106
107graph1.SetMarkerColor(ROOT.kAzure - 3)
108graph1.SetMarkerStyle(20)
109graph1.SetMarkerSize(2)
110graph1.SetLineColor(ROOT.kAzure - 3)
111graph1.SetLineWidth(2)
112
113# Draw graph1
114graph1.Draw("ALP")
115
116# Add custom x-axis labels and ticks to align with data points for better readability
117dy = ymax - ymin
118xaxislabels = []
119xaxisticks = []
120
121for i in range(len(dataset1_x_values)):
122 # Get the x-coordinate of the i-th data point
123 x = graph1.GetPointX(i)
124
125 # Add custom label for the x-axis
126 # Place the label slightly below the x-axis
127 label = ROOT.TLatex(x, -8, str(int(x)))
128 label.SetTextSize(0.03)
129 # Use a standard ROOT font
130 label.SetTextFont(42)
131 # Align text to the left and bottom relative to the anchor point
132 label.SetTextAlign(11)
133 # Rotate the label 45 degrees for better readability
134 label.SetTextAngle(45)
135 label.Draw()
136 # Keep a reference to the label to ensure it persists on the canvas
137 xaxislabels.append(label)
138
139 # Create a tick at the x-coordinate
140 # Draw a tick line below the axis
141 tick = ROOT.TLine(x, 0, x, 0 - 0.02 * dy)
142 tick.Draw()
143 # Keep a reference to the tick to ensure it persists on the canvas
144 xaxisticks.append(tick)
145
146# Configure graph2
147graph2.SetMarkerColor(ROOT.kOrange + 1)
148graph2.SetMarkerStyle(43)
149graph2.SetMarkerSize(4)
150graph2.SetLineColor(ROOT.kOrange + 1)
151graph2.SetLineWidth(2)
152
153# Draw graph2
154graph2.Draw("SAME LP")
155
156# Add a legend to distinguish Dataset 1 and Dataset 2
157legend = ROOT.TLegend(0.2, 0.75, 0.4, 0.91)
158legend.AddEntry(graph1, "Dataset 1", "lp")
159legend.AddEntry(graph2, "Dataset 2", "lp")
160legend.SetTextSize(0.03)
161legend.Draw()
162
163# Save the canvas as a PDF
164canvas.SaveAs("tgraph_comparison.pdf")
165\endcode
166
167\endpythondoc
#define f(i)
Definition RSha256.hxx:104
#define a(i)
Definition RSha256.hxx:99
@ kOrange
Definition Rtypes.h:67
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t SetLineWidth
Option_t Option_t SetTextSize
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t np
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void on
Option_t Option_t SetLineColor
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
Option_t Option_t SetTextFont
Option_t Option_t SetMarkerStyle
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t points
Option_t Option_t width
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t height
Option_t Option_t TPoint TPoint const char text
float ymin
float ymax
Color * colors
Definition X3DBuffer.c:21
A TGraph is an object made of two arrays X and Y with npoints each.
Definition TGraph.h:41
To draw Mathematical Formula.
Definition TLatex.h:18
This class displays a legend box (TPaveText) containing several legend entries.
Definition TLegend.h:23
Use the TLine constructor to create a simple line.
Definition TLine.h:22
TLine * line
RooCmdArg Save(bool flag=true)
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
leg AddEntry(h1,"Histogram filled with random numbers","f")
const Int_t n
Definition legend1.C:16
gr SetMarkerSize(1.3)
for(Int_t i=0;i< n;i++)
Definition legend1.C:18
Vector Rotate(const Vector &v, const RotationMatrix &rot)
rotation on a generic vector using a generic rotation class.
Definition VectorUtil.h:345
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
TString as(SEXP s)
Definition RExports.h:86
TMatrixT< Element > & Add(TMatrixT< Element > &target, Element scalar, const TMatrixT< Element > &source)
Modify addition: target += scalar * source.
Definition graph.py:1
th1 Draw()
th1 SetTextAlign(11)
m SetMarkerColor(kBlue)
tt SetTextAngle(45)
static void output()