在ggplot中创建预测间隔(点和功能区几何的不同数据) [英] Create prediction interval in ggplot (different data for points and ribbon geoms)

查看:68
本文介绍了在ggplot中创建预测间隔(点和功能区几何的不同数据)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ggplot2()创建一个预测间隔图.我希望只绘制原始数据帧中预测间隔的点,并绘制在另一个覆盖最小和最大x的数据帧中创建的x值序列的预测间隔功能区原始数据框中使用的值.以下是展示详细信息的MWE:

I am trying to create a prediction interval plot using ggplot2(). I hope to only plot points in the original data frame that are outside the prediction interval, and to plot the prediction interval ribbon for a sequence of x values created in another data frame that covers the minimum and maximum x values used in the original data frame. Below is a mwe to demonstrate the details:

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) 

对于如何实现这种情节的任何建议,将不胜感激.

Any advice on how to achieve this type of plot would be much appreciated.

推荐答案

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

Good work at troubleshooting. The answer is in the last error:

Error: geom_ribbon requires the following missing aesthetics: x

geom_ribbon 的x轴需要一些变量.您可以在主要的 ggplot 调用中指定 qsec ,但是此列不在 pred_interval 数据框中,因此, geom_ribbon 会得到丢失的.试试:

geom_ribbon needs some variable for the x-axis. You specify qsec in the main ggplot call, but this column is not in the pred_interval dataframe, so geom_ribbon gets lost. Try:

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) 

这篇关于在ggplot中创建预测间隔(点和功能区几何的不同数据)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆