问题
I have model prediction for mean ans confidence intervals from my data that I want to add on the graph. I know how to plot the data, but how can I add the model fitted mean and confidence intervals? For the latter geom_ribbon does not seem to do the job.
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)
回答1:
Here's one way to do it. First we use expand.grid
to make rows of each of the values we want to predict and only those. This avoids duplicates.
plot_data <- expand.grid(level = c("low", "high"), fertilizer=c("N","P"))
plot_data <- cbind(plot_data, predict(mod1, plot_data, interval="confidence"))
Not we use geom_errorbar
with the predicted interval values.
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))
来源:https://stackoverflow.com/questions/57598295/adding-confidence-intervals-from-model-predictions-in-mixed-models-in-r-ggplo