r语言 - 在 ggplot 中创建预测区间(点和带状几何的不同数据)



我正在尝试使用 ggplot2(( 创建预测区间图。我希望只绘制原始数据框中超出预测区间的点,并为在另一个数据帧中创建的 x 值序列绘制预测区间功能区,该数据帧涵盖原始数据帧中使用的最小和最大 x 值。下面是一个演示细节的mwe:

library(ggplot2) 
dat <- data.frame(qsec=mtcars$qsec, wt=mtcars$wt)
m <- lm(wt ~ qsec, data = dat) 
mpi <- cbind(dat, predict(m, interval = "prediction"))
# Keep only points that are outside the prediction interval
plotPoints <- mpi[which(!(mpi$wt > mpi$lwr & mpi$wt < mpi$upr)),]
# Create prediction interval data frame with upper and lower lines corresponding to sequence covering minimum and maximum of x values in original dataset
newx <- seq(min(mpi$qsec), max(mpi$qsec), by=0.05)
pred_interval <- predict(m, newdata=data.frame(qsec=newx), interval="prediction", level = 0.95)
pred_interval <- as.data.frame(pred_interval)
# Below are three different attempts to plot the prediction upper and lower lines as ribbons and the points outside the prediction interval as points. Each attempt gives an error which is also commented.
# Error: Object 'qsec' not found
ggplot(data=plotPoints, aes(x = qsec, y = wt)) + geom_point() + 
  geom_ribbon(data=pred_interval, aes(ymin = lwr, ymax = upr), fill = "blue", alpha = 0.2) 
# Error: Object 'wt' not found
ggplot(data=plotPoints, aes(x = qsec)) + geom_point(y = wt) + 
  geom_ribbon(data=pred_interval, aes(ymin = lwr, ymax = upr), fill = "blue", alpha = 0.2) 
# Error: geom_ribbon requires the following missing aesthetics: x
ggplot(data=plotPoints) + geom_point(aes(x = qsec, y=wt)) + 
  geom_ribbon(data=pred_interval, aes(ymin = lwr, ymax = upr), fill = "blue", alpha = 0.2) 

关于如何实现此类情节的任何建议将不胜感激。

在故障排除方面做得很好。答案在最后一个错误中:

Error: geom_ribbon requires the following missing aesthetics: x

geom_ribbon 需要一些 x 轴的变量。您在主ggplot调用中指定了qsec,但此列不在pred_interval数据帧中,因此geom_ribbon会丢失。尝试:

pred_interval$qsec = newx
ggplot(data=plotPoints, aes(x = qsec)) + geom_point(aes(y = wt)) + 
  geom_ribbon(data=pred_interval, aes(ymin = lwr, ymax = upr), fill = "blue", alpha = 0.2) 

最新更新