Search code examples
rggplot2ggpmisc

Does ggpmisc::stat_poly_eq recompute the trend line math to get the labels?


library(ggplot2)
library(dplyr)
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"),
                      facet = c("C", "D", "E", "F", "G"),
                      y2 = y * c(0.5,2),
                      w = sqrt(x))

formula <- y ~ poly(x, 3, raw = TRUE)
ggplot(my.data %>% group_by(facet, group) %>% mutate(n = n()), aes(x, y, n = n, color = facet)) +
  geom_point() +
  geom_smooth(method = "lm", formula = formula) +
  facet_grid(vars(group)) + 
  ggpmisc::stat_poly_eq(aes(label = paste(stat(rr.label), paste("N ~`=`~", n), sep = "*\", \"*")), 
                        formula = formula, parse=T)

geom_smooth will compute the math once to draw the trend line. If I then add ggpmisc::stat_poly_eq, will it recompute the math a second time to get the label?


Solution

  • Yes, they will fit it twice. I do not know of a way of avoiding this within 'ggplot2' without relying on writing a new pair of stat + geom. It could be done I think, and in fact would be a good enhancement to the package.