簡體   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