繁体   English   中英

在R — ggplot2中混合模型中的模型预测中添加置信区间?

[英]Adding confidence intervals from model predictions in mixed models in R — ggplot2?

我对要添加到图表上的数据的平均预测置信区间进行了模型预测。 我知道如何绘制数据,但是如何添加拟合均值和置信区间的模型? 对于后者,geom_ribbon似乎无法完成任务。 肥料

df <- data.frame(
  fertilizer = c("N","N","N","N","N","N","N","N","N","N","N","N","P","P","P","P","P","P","P","P","P","P","P","P","N","N","N","N","N","N","N","N","N","N","N","N","P","P","P","P","P","P","P","P","P","P","P","P"), 
  level = c("low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","low"), 
  growth = c(0,0,1,2,90,5,2,5,8,55,1,90,2,4,66,80,1,90,2,33,56,70,99,100,66,80,1,90,2,33,0,0,1,2,90,5,2,2,5,8,55,1,90,2,4,66,0,0), 
  repro = c(1,90,2,4,66,80,1,90,2,33,56,70,99,100,66,80,1,90,2,33,0,0,1,2,90,5,2,2,5,8,55,1,90,2,4,66,0,0,0,0,1,2,90,5,2,5,8,55)
)    

mod1 <- lm(growth~ fertilizer + level + fertilizer :level, df)
df$predict <- predict(mod1)
predci <- predict(mod1, interval = "confidence")
dflm = cbind(df, predci)

ggplot(dflm, aes(x=fertilizer, y=predict, color = fertilizer)) + 
  theme_bw() + 
  scale_color_manual(values=c("#E69F00", "#1B9E77")) + 
  geom_ribbon(aes(ymin = lwr, ymax = upr, fill = fertilizer, color = NULL), alpha = .15) +
  stat_summary(aes(color = fertilizer),fun.y = mean, geom = "point", size = 4, position = position_dodge(0.1)) + 
  facet_grid(.~level)

这是一种方法。 首先,我们使用expand.grid对每个我们要预测的值(仅这些值)进行排。 这样可以避免重复。

plot_data <- expand.grid(level = c("low", "high"), fertilizer=c("N","P"))
plot_data <- cbind(plot_data, predict(mod1, plot_data, interval="confidence"))

不,我们将geom_errorbar与预测的间隔值一起使用。

ggplot(plot_data, aes(fertilizer, color=fertilizer)) + 
  geom_point(aes(y=fit)) + 
  geom_errorbar(aes(ymin=lwr, ymax=upr)) + 
  scale_color_manual(values=c("#E69F00", "#1B9E77")) + 
  facet_grid(cols=vars(level))

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM