Logo ROOT  
Reference Guide
rf101_basics.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_roofit
3## \notebook
4## This tutorial illustrates the basic features of RooFit.
5##
6## \macro_code
7##
8## \date February 2018
9## \author Clemens Lange, Wouter Verkerke (C++ version)
10
11import ROOT
12
13# Set up model
14# ---------------------
15# Declare variables x,mean,sigma with associated name, title, initial
16# value and allowed range
17x = ROOT.RooRealVar("x", "x", -10, 10)
18mean = ROOT.RooRealVar("mean", "mean of gaussian", 1, -10, 10)
19sigma = ROOT.RooRealVar("sigma", "width of gaussian", 1, 0.1, 10)
20
21# Build gaussian p.d.f in terms of x,mean and sigma
22gauss = ROOT.RooGaussian("gauss", "gaussian PDF", x, mean, sigma)
23
24# Construct plot frame in 'x'
25xframe = x.frame(ROOT.RooFit.Title("Gaussian p.d.f.")) # RooPlot
26
27# Plot model and change parameter values
28# ---------------------------------------------------------------------------
29# Plot gauss in frame (i.e. in x)
30gauss.plotOn(xframe)
31
32# Change the value of sigma to 3
33sigma.setVal(3)
34
35# Plot gauss in frame (i.e. in x) and draw frame on canvas
36gauss.plotOn(xframe, ROOT.RooFit.LineColor(ROOT.kRed))
37
38# Generate events
39# -----------------------------
40# Generate a dataset of 1000 events in x from gauss
41data = gauss.generate(ROOT.RooArgSet(x), 10000) # ROOT.RooDataSet
42
43# Make a second plot frame in x and draw both the
44# data and the p.d.f in the frame
45xframe2 = x.frame(ROOT.RooFit.Title(
46 "Gaussian p.d.f. with data")) # RooPlot
47data.plotOn(xframe2)
48gauss.plotOn(xframe2)
49
50# Fit model to data
51# -----------------------------
52# Fit pdf to data
53gauss.fitTo(data)
54
55# Print values of mean and sigma (that now reflect fitted values and
56# errors)
57mean.Print()
58sigma.Print()
59
60# Draw all frames on a canvas
61c = ROOT.TCanvas("rf101_basics", "rf101_basics", 800, 400)
62c.Divide(2)
63c.cd(1)
64ROOT.gPad.SetLeftMargin(0.15)
65xframe.GetYaxis().SetTitleOffset(1.6)
66xframe.Draw()
67c.cd(2)
68ROOT.gPad.SetLeftMargin(0.15)
69xframe2.GetYaxis().SetTitleOffset(1.6)
70xframe2.Draw()
71
72c.SaveAs("rf101_basics.png")