Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
_th1.pyzdoc
Go to the documentation of this file.
1\pythondoc TH1
2
3## Drawing histograms in Python
4
5Drawing histograms is done via TH1::Draw(). Note that in interactive scripts,TCanvas::Draw() can be
6made blocking to interactively show it on the screen before continuing execution.
7\code{.py}
8c = ROOT.TCanvas()
9h = ROOT.TH1D("h1", "h1", 100, -5, 5)
10h.FillRandom("gaus", 10000)
11h.Draw("")
12
13c.Draw(block=True)
14\endcode
15
16## Fitting histograms in Python
17
18One-dimensional histograms can be fit in [Python](https://root.cern/manual/python) with a similar syntax as in C++.
19To fit a 1D histogram to one of the ROOT standard functions (e.g. a Gaussian):
20
21\code{.py}
22# Create and initialize a test histogram to fit
23myTH1D = ROOT.TH1D("th1d", "Histogram for fitting", 200, 0, 10)
24myTH1D.FillRandom("gaus", 1000)
25
26# Fit to a ROOT pre-defined Gaussian function "gaus"
27myTH1D.Fit("gaus")
28\endcode
29
30The list of standard functions in ROOT can be accessed with the TROOT::GetListOfFunctions.
31In Python, the standard functions for TF1 can be printed as follows:
32
33\code{.py}
34ROOT.TF1.InitStandardFunctions()
35
36# Print a list of available functions and their definitions
37ROOT.gROOT.GetListOfFunctions().Print()
38\endcode
39
40## Accessing results of the fit in Python
41
42To access the results of the fit, run the TH1::Fit method with the "s" option (please see the TH1::Fit(TF1*, Option_t*, Option_t*, Double_t, Double_t)
43documentation for a list of possible options).
44This will return a TFitResult which can be examined with the corresponding TFitResult methods, with the same names in Python as in C++.
45
46For example:
47
48\code{.py}
49# Re-using the TH1D defined in the earlier example code
50myResult = myTH1D.Fit("gaus", "s")
51
52# Get the fitted parameters as a vector
53myResult.Parameters()
54
55# Get the error of the first parameter
56myResult.ParError(0)
57\endcode
58
59
60## Fitting to user-defined functions in Python
611D histograms can also be fit to any user-defined function expressed as a TF1 (see the TF1 documentation for examples on how to do this).
62
63For example, a TF1 can be defined and initialized with its ROOT constructor:
64
65\code{.py}
66# Define the function, e.g. a polynomial with two parameters: y(x) = a * x^b
67myTF1 = ROOT.TF1("myFunction", "[0] * pow(x, [1])", 0, 10)
68
69# Set parameters
70myTF1.SetParameters(10.0, 4.0)
71
72# Initialize a test histogram to fit, and fit it
73myTH1D = ROOT.TH1D("th1d", "My histogram to fit", 200, 0, 10)
74myTH1D.FillRandom("myFunction", 1000)
75myTH1D.Fit("myFunction")
76\endcode
77
78A TF1 can also be defined using a Python function, for example:
79
80\code{.py}
81def myGaussian(x, pars):
82 '''
83 Defines a Gaussian function
84 '''
85 return pars[0]*np.exp(-0.5* pow(x[0] - pars[1], 2))
86
87# Initialize from the Python function with the range -5 to +5, with two parameters to fit, and a one-dimensional input x
88myTF1 = ROOT.TF1("myFunction", myGaussian, -5, 5, npar=2, ndim=1)
89
90# Create a 1D histogram and initialize it with the built-in ROOT Gaussian "gaus"
91myTH1D = ROOT.TH1D("th1d", "Test", 200, -5, 5)
92myTH1D.FillRandom("gaus", 1000)
93
94# Fit the 1D histogram to our custom Python function
95myTH1D.Fit("myFunction")
96\endcode
97
98## Pythonizations
99The TH1 class has several additions for its use from Python, which are also available in its subclasses (e.g., TH1F, TH1D).
100
101### In-Place Multiplication
102
103TH1 instances support in-place multiplication with a scalar value using the `*=` operator:
104
105\code{.py}
106import ROOT
107
108h = ROOT.TH1D("h", "h", 100, -10, 10)
109h.FillRandom("gaus", 1000)
110
111# Multiply histogram contents by 2
112h *= 2
113\endcode
114
115This operation is equivalent to calling `h.Scale(2)`.
116
117### Filling with NumPy Arrays
118
119The Fill method has been pythonized to accept NumPy arrays as input. This allows for efficient filling of histograms with large datasets:
120
121\code{.py}
122import ROOT
123import numpy as np
124
125# Create a histogram
126h = ROOT.TH1D("h", "h", 100, -10, 10)
127
128# Create sample data
129data = np.random.normal(0, 2, 10000)
130
131# Fill histogram with data
132h.Fill(data)
133
134# Fill with weights
135weights = np.ones_like(data) * 0.5
136h.Fill(data, weights)
137\endcode
138
139The Fill method accepts the following arguments when used with NumPy arrays:
140- First argument: NumPy array containing the data to fill
141- Second argument (optional): NumPy array containing the weights for each entry
142
143<em>Please note</em> that when providing weights, the length of the weights array must match the length of the data array. If weights are not provided, all entries will have a weight of 1. A ValueError will be raised if the lengths don't match:
144
145\code{.py}
146# This will raise ValueError
147data = np.array([1.0, 2.0, 3.0])
148weights = np.array([0.5, 1.0]) # Wrong length!
149h.Fill(data, weights) # Raises ValueError: "Length mismatch: data length (3) != weights length (2)"
150\endcode
151
152The original Fill method functionality is preserved for non-NumPy arguments:
153
154\code{.py}
155# Traditional filling still works
156h.Fill(1.0) # Fill single value
157h.Fill(1.0, 2.0) # Fill single value with weight
158\endcode
159
160## Further Python fitting examples
161Further examples can be found in the tutorials:
162- [combinedFit.py](combinedFit_8py.html) performs a combined (simultaneous) fit of two 1D histograms with separate functions and some common parameters.
163- [fit1.py](fit1_8py.html) reads a `TF1` and 1D histogram (created and saved in an earlier example [fillrandom.py](fillrandom__8py.html)), and fits the histogram.
164- [fitConvolution.py](fitConvolution_8py.html) fits a 1D histogram to a convolution of two functions.
165- [fitNormSum.py](fitNormSum_8py.html) fits a 1D histogram to the normalized sum of two functions (here, a background exponential and a crystal ball function).
166- [multifit.py](multifit_8py.html) fits multiple functions to different ranges of a 1D histogram.
167
168\endpythondoc
#define b(i)
Definition RSha256.hxx:100
#define c(i)
Definition RSha256.hxx:101
#define g(i)
Definition RSha256.hxx:105
#define a(i)
Definition RSha256.hxx:99
#define h(i)
Definition RSha256.hxx:106
#define e(i)
Definition RSha256.hxx:103
double Double_t
Double 8 bytes.
Definition RtypesCore.h:73
const char Option_t
Option string (const char)
Definition RtypesCore.h:80
void SetParameters(TFitEditor::FuncParams_t &pars, TF1 *func)
Restore the parameters from pars into the function.
Option_t Option_t option
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
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 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 length
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void on
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void when
void Print(GNN_Data &d, std::string txt="")
#define gROOT
Definition TROOT.h:414
void Draw(Option_t *option="") override
Draw a canvas.
Definition TCanvas.cxx:852
1-Dim function class
Definition TF1.h:182
Extends the ROOT::Fit::Result class with a TNamed inheritance providing easy possibility for I/O.
Definition TFitResult.h:34
1-D histogram with a double per channel (see TH1 documentation)
Definition TH1.h:926
1-D histogram with a float per channel (see TH1 documentation)
Definition TH1.h:878
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:109
void Draw(Option_t *option="") override
Draw this histogram with options.
Definition TH1.cxx:3056
ROOT top level object description.
Definition TROOT.h:102
RooCmdArg Parameters(const RooArgSet &params)
RVec< PromoteTypes< T0, T1 > > pow(const T0 &x, const RVec< T1 > &v)
Definition RVec.hxx:1841
RVec< PromoteType< T > > exp(const RVec< T > &v)
Definition RVec.hxx:1832
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
h1 FillRandom("gaus", 30000)
for(Int_t i=0;i< n;i++)
Definition legend1.C:18
TFitResultPtr Fit(FitObject *h1, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption, const char *goption, ROOT::Fit::DataRange &range)
Definition HFitImpl.cxx:133
void function(const Char_t *name_, T fun, const Char_t *docstring=0)
Definition RExports.h:168
TString as(SEXP s)
Definition RExports.h:87
double polynomial(DoubleArray coeffs, int nCoeffs, int lowestOrder, double x)
In pdfMode, a coefficient for the constant term of 1.0 is implied if lowestOrder > 0.
Definition MathFuncs.h:132
void initialize(typename Architecture_t::Matrix_t &A, EInitialization m)
Definition Functions.h:282
void Initialize(Bool_t useTMVAStyle=kTRUE)
Definition tmvaglob.cxx:176
constexpr Double_t C()
Velocity of light in .
Definition TMath.h:117