I am using lme4
package to run linear mixed-effect model. I would like to add the confidence interval of the fitting line per group level in a ggplot.
My data:
data
is a data frame containing: Plot_label
: charactor variable // PD_avg
: numeric variable // Year
: Factor // GS_Prec
: Numeric variable // Direction
: Factor
My code as follows:
#Run the model
mixed.lm <- lmer(PD_avg ~ log(GS_Prec) * Direction + (1|Plot_label) + (1|Year), data = data, REML=TRUE)
#Predict
pred1 <- predict(mixed.lm, newdata = data, re.form = NA)
#Plot
ggplot(data, aes(log(GS_Prec), PD_avg, colour = Direction)) +
geom_point(alpha = .2) +
facet_wrap(~Direction) +
geom_smooth(aes(y = pred1, colour = Direction), method = "lm", size = 1.5, se = T)
To add the CI, I was setting se = T
, but it did not work. So I was trying to use geom_ribbon
, but it did not work also.
I found one similar topic having the same problem (https://stats.stackexchange.com/questions/552734/r-plotting-lmer-confidence-intervals-per-faceted-group). I did follow the topic, incidentally I got a unexpected result.
My code:
gr <- ref_grid(mixed.lm, cov.keep = c("GS_Prec", "Direction"))
emm <- emmeans(gr, spec = c("GS_Prec","Direction"), level = 0.95)
emm
ggplot(data, aes(log(GS_Prec), PD_avg, colour = Direction)) +
geom_point(alpha = .2) +
facet_wrap(~Direction) +
geom_smooth(aes(y = pred1, colour = Direction), method = "lm", size = 1.5) +
geom_ribbon(data = data.frame(emm), aes(ymin = lower.CL, ymax = upper.CL, y = NULL, fill = Direction), alpha = 0.1)+
geom_smooth(aes(y = pred1, colour = Direction), method = "lm", size = 1.5)
I would like to have the length of the confidence interval should be linked to the range of points. Does anyone know how to represent the CI properly?
This is my subset data
data.1 <- data.frame(Plot_label = c("BT 1-1-3", "BT 1-1-3", "BT 1-2-1", "BT 1-2-1",
"GW 1-1-1", "GW 1-1-1", "GW 1-5-2", "GW 1-5-2",
"SP 1-5-2", "SP 1-5-2", "SP 2-8-2", "SP 2-8-2"),
PD_avg = c("1196.61", "1323.15", "1172.17", "757.18",
"1516.02", "801.87", "1422.93", "1062.10",
"1580.51", "1520.30", "1326.25", "1321.89"),
Year = c("2016", "2017", "2016", 2017,
"2016", "2017", "2016", "2017",
"2016", "2017", "2016", "2017"),
Direction = c("BT-BT", "BT-BT", "BT-BT", "BT-BT",
"GW-BT", "GW-BT", "GW-BT", "GW-BT",
"SP-SP", "SP-SP", "SP-SP", "SP-SP"),
GS_Prec = c("130.5", "190.5", "130.5", "190.5",
"130.5", "190.5", "130.5", "190.5",
"593.26", "480.29", "593.26", "593.26"))