【发布时间】:2017-05-20 13:48:40
【问题描述】:
我正在尝试使用 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)
任何关于如何实现这种情节的建议将不胜感激。
【问题讨论】: