Graph fit example within pyROOT
import numpy as np
import ROOT
from ROOT import TF1, TVirtualFitter, TGraphErrors, TCanvas, TMinuit, TFitResult, gROOT, TGraph
Welcome to JupyROOT 6.20/08
Define the data
numDat = 10
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype='d')
dx = np.array([0.1,0.1,0.5,0.1,0.5,0.1,0.5,0.1,0.5,0.1], dtype='d')
y = np.array([1.1 ,2.3 ,2.7 ,3.2 ,3.1 ,2.4 ,1.7 ,1.5 ,1.5 ,1.7 ], dtype='d')
dy = np.array([0.15,0.22,0.29,0.39,0.31,0.21,0.13,0.15,0.19,0.13], dtype='d')
Define fit function
def myNFunc(x, p):
return p[0] + x[0]*p[1] + p[2]*x[0]**2 + p[3]*x[0]**3
Create ROOT function and set start parameters
func = TF1('func',myNFunc, 0.5 ,10.5, 4)
func.SetParameters(-1.3, 2.6 , -0.24 , 0.005)
Create Graph with error bars
Graph = TGraphErrors(numDat, x, y, dx, dy)
Graph.SetTitle( 'Fit Graph' )
Graph.SetMarkerColor( 4 )
Graph.SetMarkerStyle( 21 )
Graph.SetMaximum(4.)
Graph.SetMinimum(-1.)
Start fitter and return fit result for later processing
result = Graph.Fit(func, "M E S","",0.5,10.5)
FCN=2.15982 FROM MINOS STATUS=SUCCESSFUL 90 CALLS 2039 TOTAL EDM=4.56889e-09 STRATEGY= 1 ERROR MATRIX ACCURATE EXT PARAMETER STEP FIRST NO. NAME VALUE ERROR SIZE DERIVATIVE 1 p0 -1.03327e+00 4.63548e-01 -1.99485e-03 1.64067e-03 2 p1 2.54886e+00 3.59144e-01 2.70551e-03 -5.29683e-02 3 p2 -4.84278e-01 7.01863e-02 -2.72411e-04 -7.70245e-01 4 p3 2.56882e-02 3.97082e-03 3.97082e-03 -1.30073e+00
Confidence plot
values = result.GetConfidenceIntervals(0.66, False)
interval = TGraphErrors(Graph.GetN())
for i in range(Graph.GetN()):
interval.SetPoint(i, Graph.GetX()[i], func.Eval(Graph.GetX()[i] ))
interval.SetPointError(i, 0, values[i] )
Canvas for plotting
c = TCanvas( 'c', 'A Simple Fit',700, 500)
Draw canvas and graph and 1 sigma confidence
Graph.Draw("AP")
interval.SetFillColor(21)
interval.Draw("3")
c.Draw()
Create graph for confidence interval
Compute the confidence intervals at the x points of the created graph
GraphConf = TGraphErrors(Graph.GetN())
GraphConf.SetTitle("Fit Polynomial with .95 confidence;x;f(x)")
for i in range(Graph.GetN()):
GraphConf.SetPoint(i, Graph.GetX()[i],0 )
TVirtualFitter.GetFitter().GetConfidenceIntervals(GraphConf,0.95)
Now the "GraphConf" graph contains function values as its y-coordinates and confidence intervals as the errors on these coordinates
myC = TCanvas("myC", "Confidence Intervall",800, 800);
GraphConf.SetLineColor(4)
GraphConf.Draw("AP")
Graph.SetLineColor(2)
Graph.SetMarkerStyle(21)
Graph.Draw("P SAME")
func.SetLineColor(4)
func.Draw("SAME")
myC.Draw()