点和线之间的绘图段

Plot segment between point and line

我有以下数据集:

x <- 1:5
y <- c(1, 2, 1.3, 3.75, 2.25)

我需要使用简单回归绘制适合我的数据集的直线,以及这些点:

plot(x, y, pch=19, ylim=c(0,6))
xx <- seq(0, 6, length=100)
fit <- lm(y~x)
lines(xx, predict(fit, data.frame(x=xx)))

现在我想将图中的点加入到线中,如下图(示例)所示,显示相关的预测误差:

我该怎么办?

我喜欢 broom 包,它可以为这样的事情生成一个不错的数据框:

library(broom)
aug_fit = broom::augment(fit)

with(aug_fit, segments(x0 = x, y0 = y, x1 = x, y1 = .fitted))

运行 我的 with(... segments()) 行在你的情节产生后:

我会把添加颜色、文本标签等留给你。

使用基础 r 你可以做以下事情:

x <- 1:5
y <- c(1, 2, 1.3, 3.75, 2.25)

fit <- lm(y ~ x)
plot(x, y)
abline(fit)
res <- signif(residuals(fit), 5)
pre <- predict(fit)
segments(x, y, x, pre, col = rainbow(length(x)))

使用 calibrate::textxy 添加标签很容易:

# install.packages("calibrate")
library(calibrate)
textxy(x, y, res)

使用 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 答案,与格雷戈尔的答案在精神上相似。这利用了 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")