문제

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

도움이 되었습니까?

해결책 3

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.

다른 팁

You can do this really nicely with ggplot2

library(ggplot2)
set.seed(1)     
x<-1:10
y<-3*x + 2 + rnorm(10)
m<-lm(y ~ x)
yhat<-m$fitted.values
diff<-y-yhat     
qplot(x=x, y=y)+geom_line(y=yhat)+
       geom_segment(aes(x=x, xend=x, y=y, yend=yhat, color="error"))+
       labs(title="regression errors", color="series")

enter image description here

There is a much simpler solution:

segments(x, y, x, predict(ols))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top