Wolfram Research

Function Repository Resource:

TheilSenLine (1.0.0) current version: 1.1.0 »

Source Notebook

Fit a line through a set of points using the Theil–Sen estimator

Contributed by: Rauan Kaldybayev

ResourceFunction["TheilSenLine"][data]

uses the Theil–Sen estimator to fit a line through a set of points represented by data.

ResourceFunction["TheilSenLine"][xlist,ylist]

uses the Theil–Sen estimator to fit a line through a set of points, where xlist and ylist respectively give the x and y coordinates of the points.

Details

ResourceFunction["TheilSenLine"][data,x] or ResourceFunction["TheilSenLine"][xlist,ylist,x] returns the equation of a line mx+b (instead of {m,b}), where x is the predictor of the model and can be any symbol.

Examples

Basic Examples (2) 

Fit a line through the points (0,1),(1,1),(2.5,3) using the Theil–Sen estimator:

In[1]:=
ResourceFunction["TheilSenLine"][{{0, 1}, {1, 1}, {2.5, 3}}]
Out[1]=

The output is of the form {m,b}, which represents a line fit of the form y=mx+b. Compare the fitted line to the original points:

In[2]:=
Show[ListPlot[{{0, 1}, {1, 1}, {2.5, 3}}, PlotStyle -> {PointSize -> Large}], Plot[%[[1]] x + %[[2]] // Evaluate, {x, 0, 2.5}, PlotStyle -> ColorData[97, 2]]]
Out[2]=

Scope (2) 

Supply data given in the form of separate lists for the x and y coordinates:

In[3]:=
ResourceFunction["TheilSenLine"][{0, 1, 2.5}, {1, 1, 3}]
Out[3]=

Return a formula for the model by passing the predictor as an additional argument:

In[4]:=
ResourceFunction["TheilSenLine"][{{0, 1}, {1, 1}, {2.5, 3}}, x]
Out[4]=

Publisher

Wolfram Summer Camp

Version History

  • 1.1.0 – 27 February 2023
  • 1.0.1 – 10 February 2023
  • 1.0.0 – 20 July 2021

Source Metadata

Related Resources

Author Notes

The code for this function is based on a piece of code written by the StackExchange user J.M. in answering the question "How can the Theil-Sen estimator be made to work on larger datasets?" on Mathematica Stack Exchange.

License Information