Search code examples
rplotvisualizationlinespoints

Regression Line to Data Points/ How to create vertical lines?


How one can get the following visualization in R (see below): let's consider a simple case of three points.

# Define two vectors
x <- c(12,21,54)
y <- c(2, 7, 11)

# OLS regression
ols <- lm(y ~ x)

# Visualisation
plot(x,y, xlim = c(0,60), ylim =c(0,15))    
abline(ols, col="red")

What I desire is, to draw the vertical distance lines from OLS line (red line) to points. enter image description here


Solution

  • If you construct a matrix of points, you can use apply to plot the lines like this:

    Create a matrix of coordinates:

    cbind(x,x,y,predict(ols))
    #   x  x  y          
    #1 12 12  2  3.450920
    #2 21 21  7  5.153374
    #3 54 54 11 11.395706
    

    This can be plotted as:

    apply(cbind(x,x,y,predict(ols)),1,function(coords){lines(coords[1:2],coords[3:4])})
    

    effectively a for loop running over the rows of the matrix and plotting one line for each row.