Function Repository Resource:

TrendLine

Source Notebook

Trend line of a given set of data

Contributed by: Jan Mangaldan

ResourceFunction["TrendLine"][{{x1,y1},{x2,y2},}]

returns an InfiniteLine representing the least-squares line fit of the points {xi,yi}.

Examples

Basic Examples (3) 

Here is some data:

In[1]:=
data = {{0, 1}, {1, 0}, {3, 2}, {5, 4}};

The trend line for the data:

In[2]:=
tLine = ResourceFunction["TrendLine"][data]
Out[2]=

Show the data and the trend line together:

In[3]:=
ListPlot[data, Epilog -> {Directive[
RGBColor[0.368417, 0.506779, 0.709798], 
AbsoluteThickness[1.6]], tLine}, PlotStyle -> ColorData[97, 4]]
Out[3]=

Properties and Relations (3) 

Here is some data:

In[4]:=
data = {{0, 1}, {1, 0}, {3, 2}, {5, 4}};

The linear function corresponding to the result of TrendLine is equivalent to the results returned by functions such as Fit and LinearModelFit:

In[5]:=
f1 = FullSimplify[
  RegionMember[
   ResourceFunction["TrendLine"][
    data], {\[FormalX], \[FormalY]}], {\[FormalX], \[FormalY]} \[Element] Reals]
Out[5]=
In[6]:=
f2 = (\[FormalY] == Fit[data, {1, \[FormalX]}, \[FormalX]])
Out[6]=
In[7]:=
LinearModelFit[data, {1, \[FormalX]}, \[FormalX]] // Normal
Out[7]=

Show the lines together:

In[8]:=
ContourPlot[{f1, f2} // Evaluate, {\[FormalX], 0, 5}, {\[FormalY], 0, 5}, ContourStyle -> {AbsoluteThickness[4], AbsoluteThickness[2]}]
Out[8]=

Version History

  • 1.0.0 – 02 August 2022

Related Resources

Author Notes

Trend lines corresponding to other fitting norms (e.g. 1, ∞) will be implemented in a future version.

License Information