# How to use histograms to create a fit function (fit using histograms)

**URL:** <https://root-forum.cern.ch/t/how-to-use-histograms-to-create-a-fit-function-fit-using-histograms/49657>\
**Category:** Evolution Proposals, Apps & Ideas\
**Created:** [April 20, 2022, 7:14pm UTC](https://root-forum.cern.ch/t/how-to-use-histograms-to-create-a-fit-function-fit-using-histograms/49657 "2022-04-20T19:14:49Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![assosiation](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/assosiation/32/34837_2.png) [@assosiation](https://root-forum.cern.ch/u/assosiation)\
**Post date:** [April 20, 2022, 7:14pm UTC](https://root-forum.cern.ch/t/how-to-use-histograms-to-create-a-fit-function-fit-using-histograms/49657/1 "2022-04-20T19:14:49Z")

</div>

here is the example code on how to make a fit function (TF1) from existing histograms and use it to fit the ‘data’ in another histogram. Same approach can be used to create the fit function from arrays and other enumerable objects.

done using PyROOT

```auto
import ROOT

histograms={}

histograms[1] = ROOT.TH1F("h1","",100,-3,3)
histograms[2] = ROOT.TH1F("h2","",100,-3,3)
histograms[3] = ROOT.TH1F("h3","",100,-3,3)

histograms[1].FillRandom("gaus",10000)
histograms[2].FillRandom("gaus",2000)
histograms[3].FillRandom("gaus",3000)

def Onetracklengthfunc(x,par):
	bin=histograms[2].GetXaxis().FindBin(x[0])
	func=par[0]*histograms[2].GetBinContent(bin)+par[1]*histograms[3].GetBinContent(bin)
	return func

fitfunc=ROOT.TF1("fitfunc",Onetracklengthfunc,-3,3,2)

histograms[1].Fit("fitfunc")

ROOT.gStyle.SetOptFit()

histograms[1].Draw("P E4")

a=raw_input("hit enter to exit")

```
