Function Repository Resource:

PlaneOfBestFit

Source Notebook

Get the hyperplane that best fits a set of points

Contributed by: Jason Biggs

ResourceFunction["PlaneOfBestFit"][{p1,p2,}]

returns an InfinitePlane that minimizes the sum of squares of orthogonal distances to the 3D points pi.

Details

In two dimensions, ResourceFunction["PlaneOfBestFit"] returns an InfiniteLine.
In dimensions higher than three, ResourceFunction["PlaneOfBestFit"] returns a Hyperplane.

Examples

Basic Examples (3) 

Generate a set of random points in space:

In[1]:=
SeedRandom@42;
transform = RotationTransform[RandomReal[{0, 2 \[Pi]}], Normalize@RandomReal[1, 3]];
points = transform@Thread[{
     RandomReal[{-100, 100}, 1000],
     RandomReal[{-100, 100}, 1000], RandomReal[{-10, 10}, 1000]
     }];
Graphics3D@Point@points
Out[4]=

Find the plane of best fit:

In[5]:=
plane = ResourceFunction["PlaneOfBestFit"][points]
Out[5]=

Show the best­fit plane along with the points:

In[6]:=
Graphics3D[{Point@points, Red, Opacity[.5], plane}]
Out[6]=

Scope (2) 

Create a best-fit line for points in 2D. First generate a set of random data:

In[7]:=
SeedRandom@42;
transform = RotationTransform[RandomReal[{0, 2 \[Pi]}], Normalize@RandomReal[1, 2]];
points = transform@
   Thread[{RandomReal[{-100, 100}, 1000], RandomReal[{-10, 10}, 1000]}];
Graphics@Point@points
Out[10]=

Find the line of best fit:

In[11]:=
line = ResourceFunction["PlaneOfBestFit"][points]
Out[11]=

Show the best­fit line along with the points:

In[12]:=
Graphics[{Style[Point@points, Lighter[Red]], Blue, line}]
Out[12]=

Create points in 4D such that the spread along the last axis is much less than along the other three:

In[13]:=
SeedRandom@4224;
points = Thread[{RandomReal[{-100, 100}, 1000],
    RandomReal[{-100, 100}, 1000],
    RandomReal[{-100, 100}, 1000], RandomReal[{-10, 10}, 1000]}];

Create a best-fit 3D hyperplane to these points and obtain a normal vector close to {0,0,0,1}:

In[14]:=
ResourceFunction["PlaneOfBestFit"][points]
Out[14]=

Version History

  • 1.0.1 – 24 August 2021
  • 1.0.0 – 22 April 2020

Related Resources

License Information