Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
rf203_ranges.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_roofit
3## \notebook
4## Addition and convolution: fitting and plotting in sub ranges
5##
6## \macro_image
7## \macro_code
8## \macro_output
9##
10## \date February 2018
11## \authors Clemens Lange, Wouter Verkerke (C++ version)
12
13import ROOT
14
15# Set up model
16# ---------------------
17
18# Construct observables x
19x = ROOT.RooRealVar("x", "x", -10, 10)
20
21# Construct gaussx(x,mx,1)
22mx = ROOT.RooRealVar("mx", "mx", 0, -10, 10)
23gx = ROOT.RooGaussian("gx", "gx", x, mx, 1.0)
24
25# px = 1 (flat in x)
26px = ROOT.RooPolynomial("px", "px", x)
27
28# model = f*gx + (1-f)px
29f = ROOT.RooRealVar("f", "f", 0.0, 1.0)
30model = ROOT.RooAddPdf("model", "model", [gx, px], [f])
31
32# Generated 10000 events in (x,y) from pdf model
33modelData = model.generate({x}, 10000)
34
35# Fit full range
36# ---------------------------
37
38# Fit pdf to all data
39r_full = model.fitTo(modelData, Save=True, PrintLevel=-1)
40
41# Fit partial range
42# ----------------------------------
43
44# Define "signal" range in x as [-3,3]
45x.setRange("signal", -3, 3)
46
47# Fit pdf only to data in "signal" range
48r_sig = model.fitTo(modelData, Save=True, Range="signal", PrintLevel=-1)
49
50# Plot/print results
51# ---------------------------------------
52
53# Make plot frame in x and add data and fitted model
54frame = x.frame(Title="Fitting a sub range")
55modelData.plotOn(frame)
56model.plotOn(frame, Range="Full", LineColor="r", LineStyle="--") # Add shape in full ranged dashed
57model.plotOn(frame) # By default only fitted range is shown
58
59# Print fit results
60print("result of fit on all data ")
61r_full.Print()
62print("result of fit in in signal region (note increased error on signal fraction)")
63r_sig.Print()
64
65# Draw frame on canvas
66c = ROOT.TCanvas("rf203_ranges", "rf203_ranges", 600, 600)
67ROOT.gPad.SetLeftMargin(0.15)
68frame.GetYaxis().SetTitleOffset(1.4)
69frame.Draw()
70
71c.SaveAs("rf203_ranges.png")