# How to fill 2d histo with function?

**URL:** <https://root-forum.cern.ch/t/how-to-fill-2d-histo-with-function/39972>\
**Category:** Newbie\
**Tags:** hist\
**Created:** [June 18, 2020, 10:09pm UTC](https://root-forum.cern.ch/t/how-to-fill-2d-histo-with-function/39972 "2020-06-18T22:09:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Va\_Findesiecle](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/va_findesiecle/32/20144_2.png) [@Va\_Findesiecle](https://root-forum.cern.ch/u/Va_Findesiecle)\
**Post date:** [June 18, 2020, 10:09pm UTC](https://root-forum.cern.ch/t/how-to-fill-2d-histo-with-function/39972/1 "2020-06-18T22:09:48Z")

</div>

Hello everyone,

I have 2 TH2F histos, 1st one with data, 2nd one with background that I want to subtract from the data. After the second diagram has been fitted with function

```auto
Double_t fun2(Double_t *x, Double_t *par) {
Double_t z2 = x[0]*x[0]/par[0]/par[0] + x[1]*x[1]/par[1]/par[1];
z2 *= par[2]*par[2];
return -sqrt(z2) + par[3];
}

```

I want to subtract background, as I see [here](https://root.cern.ch/root/roottalk/roottalk00/0894.html), I should fill TH2F using my function like this

```auto
for (int i=0;i<nb;i++)
 {
   float x=h3->GetBinCenter(i);
   float y=fun->Eval(x);
   h3->Fill(y);
 }

```

Сan anyone tell me what this cycle looks like in my TH2F case?

thanks

---

<div class="post-metadata">

**Author:** ![StephanH](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/s/c68b51/32.png) [@StephanH](https://root-forum.cern.ch/u/StephanH)\
**Post date:** [June 19, 2020, 9:01am UTC](https://root-forum.cern.ch/t/how-to-fill-2d-histo-with-function/39972/2 "2020-06-19T09:01:01Z")

</div>

Use the functions from TH2 [here](https://root.cern.ch/doc/master/classTH2.html) (Also note that TH2 derives from TH1. You can unfold the TH1 section.)

Make a [TF2](https://root.cern.ch/doc/master/classTF2.html) from your fit function, and then use [myHistogram-\>Add(myTF2, -1)](https://root.cern.ch/doc/master/classTH1.html#a6e3008f571628f0c9d17d754c8b88730) to subtract the function from the histogram.
