## Fitting a Linear Line to Data Points

A line of best fit is a line that is the best approximation of a given set of data. This line can be linear, exponential, logarithmic, polynomial, a power average or a moving average and will depend on the type of data you have and the purpose of the approximated line. Your dataset can even be in 3 dimensions.

I'm only going to look at 2D data (ordered pairs) and the Least Square Method to find a straight line () that best fit the given data points.

I've implemented the Least Squares Method using Processing and shall explain the code together with the math.

In order to manage all the data Points, I've created a very simple class called . This class is used to create new points and only has one method () which displays a single data point.

class Points { float xPos, yPos; Points(float _x, float _y) { xPos = _x; yPos = _y; } void display() { stroke(0); fill(0); ellipse(xPos, yPos, 10,10); } }

#### Step 1:

Calculate the mean of all the -values

and all the -values.

where is the total number of data points.

What these formulas do is add all the -values and divide the total by the number of -values. This is also done for all the -values.

int maxPoints = dataPoints.size(); for (int i=0; i < maxPoints; i++) { meanX += dataPoints.get(i).xPos / maxPoints; meanY += dataPoints.get(i).yPos / maxPoints; }

This is a straight forward loop. It retreives each data point's and value, divide it by the variable , which is the number of points currently on the screen, and then add it to variables called and respectively.

#### Step 2:

Calculate the slope () of the straight line with this formula:

float mNumer = 0.0; //Numerator used to calculate m float mDenom = 0.0; //Denominator used to calculate m for (int n = 0; n < maxPoints; n++) { mNumer += (dataPoints.get(n).xPos - meanX)*(dataPoints.get(n).yPos - meanY); mDenom += pow((dataPoints.get(n).xPos - meanX),2); } float m = mNumer / mDenom;

I've decide to calculate the numerator and denominator separately in order to have it more closely resemble the formula. In line , the final value for is calculated.

#### Step 3:

Using the straight line formula we now calculate the -intercept:

float c = meanY - m*meanX;

#### Step 4

Using the values for and , draw a straight line.

line(0,c,width,m*width+c);

In order to draw a straight line we need 2 points. I've selected points on the edges of the display area in order to keep the math a bit simpler.

The line is drawn from point to . The starting points' , is just and is the point on the -axis where the straight line will cross it, so it is just .

It is a bit trickier for point 2. Point 2's is the of the display area, essentially the maximum value can ever be. Point 2's value is calculated by substituting (which is the width of the display area) and (previously calculated) into the straight line formula .

### Complete Program

The complete program, is shown below and can be copied and pasted into an empty sketch.

//A Least Squares Line Fit algorithm ArrayList<Points> dataPoints = new ArrayList<Points>(); void setup() { size(500,500); frameRate(10); //Set screen refresh } void draw() { clear(); background(200); textSize(10); fill(0); text("mouse LEFT = Add/Remove data point", 10,height - 20); text("mouse RIGHT = clear all data points", 10, height - 10); //Display all the points for (Points p: dataPoints) { p.display(); } plotLine(); } void plotLine() { float meanX = 0.0; float meanY = 0.0; float mNumer = 0.0; float mDenom = 0.0; int maxPoints = dataPoints.size(); for (int n=0; n < maxPoints; n++) { meanX += dataPoints.get(n).xPos / maxPoints; meanY += dataPoints.get(n).yPos / maxPoints; } for (int n = 0; n < maxPoints; n++) { mNumer += (dataPoints.get(n).xPos - meanX)*(dataPoints.get(n).yPos - meanY); mDenom += pow((dataPoints.get(n).xPos - meanX),2); } float m = mNumer / mDenom; float c = meanY - m*meanX; line(0,c,width,m*width+c); } //Use mousePressed to create new dataPoints void mousePressed() { boolean dataPointFound = false; int idx = 0; if (mousePressed && (mouseButton == LEFT)) { //Step through all existing dataPoints to see if mouseX and mouseY is close to existing dataPoint xPos and yPos value for (int k = 0; k < dataPoints.size(); k++) { float distToDataPoint = dist(mouseX,mouseY, dataPoints.get(k).xPos, dataPoints.get(k).yPos); //If it is then set the flag if (distToDataPoint < 5) { dataPointFound = true; idx = k; } } //If flag set, then remove point from dataPoints if (dataPointFound) { dataPoints.remove(idx); } else { dataPoints.add(new Points(mouseX,mouseY)); } println("Amount of dataPoints : "+dataPoints.size()); } //Clears all the data when the RIGHT mouse button is pressed if (mousePressed && (mouseButton == RIGHT)) { dataPoints.clear(); } } class Points { float xPos, yPos; Points(float _x, float _y) { xPos = _x; yPos = _y; } void display() { stroke(0); fill(0); ellipse(xPos, yPos, 10,10); } }