How to add stat results to a ggplot regressions with random effects and facet_wrap using the fitted function?

39 views Asked by At

This is a continuation of my previous question listed here and works off of the lme4 tutorial for sleepstudy here.

My 1st question is how can I use ggplot to graph a regression with random effects using facit wrap and provide the r2.adj and pval for each individual regression, not the regression of all datapoints.

The second question continues with the first question, but how do I add end of lines using annotation_custom() so that the stats show up in the upper left corner while the y=mx+b, r2.adj, and the pval are each on their own line, allowing the fontsize to be larger.

library(lme4)
library(ggplot2)
library(grid)
library(ggpmisc)
library(scales)
library(performance)
library(car)

str(sleepstudy)
data("sleepstudy")

ggplot.model.labels  <- function (model.num, df) {

  datafit = fitted(model.num)
  r2 <- round(performance::r2_nakagawa(model.num)$R2_conditional, 3)
  pval <-  scales::pvalue(car::Anova(model.num, test = "F")$`Pr(>F)`, add_p = TRUE)
  ggplot(df, aes(Days, Reaction, group=Subject, colour=Subject)) +
    geom_point() +
    geom_line(aes(y=datafit), linetype=1) +
    annotation_custom(grid::textGrob(
      bquote(bold(~y == 
                    .(round(fixef(model.num)[1], 3)) + .(round(fixef(model.num)[2], 3)) * x) ~
               ~~~italic(paste(.(pval))~~~R^2 == .(r2))),
      x = 0.05, y = 0.9, hjust = 0, gp = gpar(col = "black", fontsize = 5))) +
    
    facet_wrap(~Subject, ncol=9) +
    scale_x_continuous(limits=c(0, 10),breaks=c(0,10)) +
    theme_minimal()
}

model4 <- lmer(Reaction ~ 1 + Days + (1 + Days | Subject), sleepstudy)
ggplot.model.labels (model4, sleepstudy)

Image 1

0

There are 0 answers