使用ggplot:
library(ggplot2)
#ggplot needs a dataframe
dat <- data.frame(x=x,y=y)
fit <- lm(y~x,data=dat)
#add predicted y for each x, to enable segment drawing
dat$pred <- predict(fit, dat)
with thanks to JasonAizkalns: adding labels too
dat$pred <- predict(fit, dat)
dat$pred_error <- dat$y - dat$pred
dat$vjust <- sign(dat$pred_error)*-1.1 #labels can appear above/below points now
p1 <- ggplot(dat, aes(x=x,y=y, color=factor(x)))+
geom_point(size=2) +
geom_segment(aes(x=x,xend=x,y=y,yend=pred)) +
geom_abline(intercept=coefficients(fit)[1],slope=coefficients(fit)[2]) +
geom_text(aes(label=round(pred_error,2),vjust=vjust))+
ylim(c(0,5))+
xlim(c(0,5))+
theme_bw()+
theme(legend.position="none")
p1
另一个 ggplot2
的答案,与 Gregor 的答案类似。这里使用了 fortify.lm
,你可以将lm
回归的结果传递给ggplot
。要查看 fortify 的作用,可以查看对象 fortify(fit)
。
# Your data and linear model
x <- 1:5
y <- c(1, 2, 1.3, 3.75, 2.25)
fit <- lm(y~x)
# Plot
library(ggplot2)
ggplot(fit, aes(x=x, y=y, xend=x, yend=y, col=factor(x), label=round(.resid, 2))) +
geom_point() +
geom_line(aes(x=x, y=.fitted), inherit.aes=FALSE) +
geom_segment(aes(y=.fitted)) +
geom_text(aes(vjust=-1*sign(.resid))) +
theme(legend.position="none")