点与直线之间的绘图部分

4

我有以下数据集:

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

现在我想把图中的点连接成线,如下面(示例)图片所示,显示相关的预测误差:

enter image description here

我该怎么做?

4个回答

4

使用基础的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轻松添加标签:

plot

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

plot with labels


1
我喜欢使用 broom 包来生成像这样的漂亮数据框:
library(broom)
aug_fit = broom::augment(fit)

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

在你的绘图后运行我的with(... segments())代码将产生以下结果:

enter image description here

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


0

使用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

enter image description here


我已经编辑了答案,谢谢。通常在geom_text中,我喜欢将标签映射到aes内部,并将始终相同的内容设置在aes之外。 - Heroka

0

另一个 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")

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