Fit a linear regression to a 3D plot

Please read tips for efficient and successful posting and posting code

ROOT Version: 6.30/06
Platform: ubuntu
Compiler: Not Provided

I save my data in an textfile and it it loos like this (2 21 0 4 13 1 15 31 2) i.e x1,y1,z1,x2,y2,z2,x3,y3,z3. I plotted this to a 3D histogram but I have trouble with fitting a linear regression through the data set. I attach my macro.
FitMuonTrajectory.C (1.6 KB)


It is hard to understand what exactly the problem is. Can you reduce the example to a few lines, make explicit what you expect and expose what you get?


You need to use TF2 instead of TF1 because your fit function is two-dimensional, as you write in the formula and in the comment. That is a mistake for sure.

Try with TF2 and see if it works…

Thanks TF2 works fine. How could I modify this so that fit is linear regression in xy and xz plane?

You could create two TGraphs and fill them with the x, y, and x, z positions, respectively.
And then fit each independently with a linear function?

Yes but I thought I could all at once. I guess I will just have to create two TGraphs then. Once again thanks for the help.

In principle if you have the formula for the 3D line.

It is easy to manually get it. It is just a linear algebra exercise.

Set z=0, and it gives you the equation for the line in xy
Set y=0, and it gives you the equation for the line in xz

I just noticed that in your function, you actually use the equation for the plane, not the 3D line!

I guess that is not what you intend to do.

I googled, and I found a ROOT example that does 3D line fit. You can use that as an inspiration.


Woww!! That helps a lot. Thank you so much.!!!