The data has two factors. I ran a simple lmer for the model. I want to plot the data using facet_plot in ggplot. I want to display the equation and R2. Here is my attempt. I don't know to facet within the lm_eqn and then display correspond to the plots.
library(lme4)
library(ggplot2)
library(ggeffects)
set.seed(123)
df <- data.frame(xaxis = rnorm(300, 2, 3), yaxis = rnorm(300,8,3), rfactor = rep(c("A","B","C"), times = 100), species = rep(c("AA","BB"), each = 150))
fit <- lmer(yaxis ~ xaxis + species + (1|rfactor), data= df)
summary(fit)
pred1 <- ggpredict(fit, c("xaxis", "species"))
pred1 <- dplyr::rename(pred1, xaxis = x, species = group)
p <- ggplot(df, aes(x = xaxis, y = yaxis, color = species, group = species)) +
theme_classic() +
geom_point() +
facet_grid(. ~ species) +
geom_ribbon(
data = pred1,
aes(x = xaxis, ymin = conf.low, ymax = conf.high, group = species),
fill = "grey80", inherit.aes = FALSE, alpha = .3
) +
geom_line(
data = pred1,
aes(x = xaxis, y = predicted, group = species),
inherit.aes = FALSE
)
To add the equations + R2:
lm_eqn <- function(df){
m <- lmer(yaxis ~ xaxis + species + (1|rfactor), df);
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(unname(coef(m)[1]), digits = 2),
b = format(unname(coef(m)[2]), digits = 2),
r2 = format(summary(m)$r.squared, digits = 3)))
as.character(as.expression(eq));
}
p + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)

