【问题标题】:Create prediction interval in ggplot (different data for points and ribbon geoms)在 ggplot 中创建预测区间(点和带状几何的不同数据)
【发布时间】: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) 

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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

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

    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) 
    

    【讨论】:

    • 感谢您在这里分享您的想法。当我运行您的解决方案“eval(expr, envir, enclos) 中的错误:找不到对象'wt'”时,我仍然收到错误。
    • 好吧,我相信这需要做: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)
    • @GreenStone 哦,是的,如果 geom_ribbon 包含在主情节中,它似乎仍在寻找 y 美学。如果可行,我将编辑答案,并考虑接受它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2017-11-10
    • 2015-02-10
    • 1970-01-01
    • 2019-07-18
    • 2021-08-29
    相关资源
    最近更新 更多