Search code examples
rggplot2ggpmisc

Coefficients per facet with output.type="numeric" in ggpmisc::stat_poly_eq


ggpmisc::stat_poly_eq has an option output.type = "numeric" allowing to get the estimates of the parameters of the fitted model. Below is my attempt to use it with facet_wrap. I get a different per facet but the coefficients are the same in the two facets. Do I do something wrong, or is it a bug?

library(ggpmisc)

set.seed(4321)
x <- 1:100
y <- (x + x^2 + x^3) + rnorm(length(x), mean = 0, sd = mean(x^3) / 4)
my.data <- data.frame(x = x, 
                      y = y,
                      group = c("A", "B"))
my.data[my.data$group=="A",]$y <- my.data[my.data$group=="A",]$y + 200000

formula <- y ~ poly(x, 1, raw = TRUE)

myformat <- "Intercept: %s\nSlope: %s\nR²: %s"
ggplot(my.data, aes(x, y)) + 
  facet_wrap(~ group) + 
  geom_point() +
  geom_smooth(method = "lm", formula = formula) +
  stat_poly_eq(formula = formula, output.type = "numeric",
               mapping = aes(label = 
                               sprintf(myformat,
                                       formatC(stat(coef.ls)[[1]][[1, "Estimate"]]),
                                       formatC(stat(coef.ls)[[1]][[2, "Estimate"]]),
                                       formatC(stat(r.squared))))) 

enter image description here


Edit

We have to catch the panel number. It is strange that formatC(stat(as.integer(PANEL))) returns the panel number per facet:

enter image description here

but however formatC(stat(coef.ls)[[stat(as.integer(PANEL))]][[1, "Estimate"]]) does not work, because here PANEL = c(1,2).


Solution

  • Ok, I figured it out.

    ggplot(my.data, aes(x, y)) + 
      facet_wrap(~ group) + 
      geom_point() +
      geom_smooth(method = "lm", formula = formula) +
      stat_poly_eq(
        formula = formula, output.type = "numeric",
        mapping = aes(label = 
                        sprintf(myformat,
                                c(formatC(stat(coef.ls)[[1]][[1, "Estimate"]]), 
                                  formatC(stat(coef.ls)[[2]][[1, "Estimate"]])),
                                c(formatC(stat(coef.ls)[[1]][[2, "Estimate"]]), 
                                  formatC(stat(coef.ls)[[2]][[2, "Estimate"]])),
                                formatC(stat(r.squared))))) 
    

    enter image description here