And*_*d_R 3 plot visualization r lines points
如何在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")
Run Code Online (Sandbox Code Playgroud)
我想要的是,从OLS线(红线)到点绘制垂直距离线.
你可以很好地做到这一点 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")
Run Code Online (Sandbox Code Playgroud)
