回归线与数据点/ 如何创建垂直线?

3

如何在R中获得以下可视化效果(见下文): 让我们考虑一个简单的三点案例。

# 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")

我希望的是,从OLS线(红线)向点绘制垂直距离线。 enter image description here

我认为这是一个有用的问题。也许考虑编辑标题,改成更容易搜索的内容,比如“在拟合/回归线和数据点之间绘制垂直线”或类似的内容。 - rmbaughman
3个回答

7

您可以使用 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


3
有一个更简单的解决方案:
segments(x, y, x, predict(ols))

1
这个运行得非常好!你也可以添加参数 col="red" 来使线条变成红色。segments(x, y, x, predict(ols), col="red") - rvbarreto

2
如果您构建了一个点的矩阵,可以使用apply函数绘制线条,如下所示:
创建一个坐标矩阵:
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

这可以绘制成:
apply(cbind(x,x,y,predict(ols)),1,function(coords){lines(coords[1:2],coords[3:4])})

实际上,这是一个针对矩阵行进行循环处理,并绘制每行数据的线条的for循环。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接