ggplot:将回归线扩展到具有不同线型的预测值

ggplot: Extend regression line to predicted value with different linetype

有没有一种简单的方法可以将虚线从实回归线的末端延伸到预测值?

下面是我的基本尝试:

x = rnorm(10)
y = 5 + x + rnorm(10,0,0.4)

my_lm <- lm(y~x)
summary(my_lm)

my_intercept <- my_lm$coef[1]
my_slope <- my_lm$coef[2]
my_pred = predict(my_lm,data.frame(x = (max(x)+1)))

ggdf <- data.frame( x = c(x,max(x)+1), y = c(y,my_pred), obs_Or_Pred = c(rep("Obs",10),"Pred") )

ggplot(ggdf, aes(x = x, y = y, group = obs_Or_Pred ) ) +
     geom_point( size = 3, aes(colour = obs_Or_Pred) ) + 
     geom_abline( intercept = my_intercept, slope = my_slope, aes( linetype = obs_Or_Pred ) )

这没有给出我希望看到的输出。我看过关于 SO 的其他一些答案,但没有看到任何东西 simple.The 我想到的最好的是:

ggdf2 <- data.frame( x = c(x,max(x),max(x)+12), y = c(y,my_intercept+max(x)*my_slope,my_pred), obs_Or_Pred = c(rep("Obs",8),"Pred","Pred"), show_Data_Point = c(rep(TRUE,8),FALSE,TRUE) )

ggplot(ggdf2, aes(x = x, y = y, group = obs_Or_Pred ) ) +
     geom_point( data = ggdf2[ggdf2[,"show_Data_Point"],] ,size = 3, aes(colour = obs_Or_Pred) ) + 
     geom_smooth( method = "lm", se=F, aes(colour = obs_Or_Pred, linetype=obs_Or_Pred) )
 

这给出了正确的输出,但我必须包含一个额外的列来指定我是否要显示数据点。如果我不这样做,我将得到这两个图中的第二个,它在拟合回归线的末尾有一个额外的点:

有没有更简单的方法告诉 ggplot 从线性模型中预测出单个点并为其画一条虚线?

您可以仅使用实际数据绘制点并构建预测数据框以添加线条。请注意 max(x) 出现两次,因此它可以同时作为 Obs 线和 Pred 线的端点。我们还使用 shape 美学,以便我们可以删除点标记,否则会出现在 Pred.

的图例键中
# Build prediction data frame
pred_x = c(min(x),rep(max(x),2),max(x)+1)
pred_lines = data.frame(x=pred_x,
                        y=predict(my_lm, data.frame(x=pred_x)),
                        obs_Or_Pred=rep(c("Obs","Pred"), each=2))

ggplot(pred_lines, aes(x, y, colour=obs_Or_Pred, shape=obs_Or_Pred, linetype=obs_Or_Pred)) +
  geom_point(data=data.frame(x,y, obs_Or_Pred="Obs"), size=3) +
  geom_line(size=1) +
  scale_shape_manual(values=c(16,NA)) +
  theme_bw()

半丑:可以使用scale_x_continuous(limits =设置用于预测的x值范围。首先用 fullrange = TRUE 绘制预测线,然后在顶部添加 'observed' 线。请注意,重叠绘制并未完美呈现,您可能希望稍微增加观察线的大小。

ggplot(d, aes(x, y)) +
  geom_point(aes(color = "obs")) +
  geom_smooth(aes(color = "pred", linetype = "pred"), se = FALSE, method = "lm",
                                                      fullrange = TRUE) +
  geom_smooth(aes(color = "obs", linetype = "obs"), size = 1.05, se = FALSE, method = "lm") +
  scale_linetype_discrete(name = "obs_or_pred") +
  scale_color_discrete(name = "obs_or_pred") +
  scale_x_continuous(limits = c(NA, max(x) + 1))


不过,我倾向于同意 Gregor 的观点:"ggplot is a plotting package, not a modeling package"。