I am interested in adding a random effect to a ggplot using stat_poly_eq().
library (ggplot2)library(ggpmisc)data (mtcars)mtcars$gear <- factor (mtcars$gear)mtcars$cyl <- factor (mtcars$cyl)transmission <- data.frame ( code = c(1, 0), type = c("manual", "automatic"))mtcars$transmission <- setNames (transmission$type, transmission$code) [as.character (mtcars$am)]my.formula <- y ~ x p <- ggplot (data = mtcars, aes(x=hp, y=mpg, group = 1)) + facet_wrap (~transmission, strip.position = "top", scales = "fixed", nrow = 1) + ggtitle ("car horsepower (hp) to effiency (mpg) based on cylinder and number of gears for American vs others cars") + geom_point ( size = 6, shape = 16, aes ( shape=cyl, color=cyl) ) + scale_color_manual (name = "number of cylinder", labels = c (paste (levels(mtcars$cyl), "cylinders")), values = c("turquoise", "orange", "red")) + geom_smooth (data = mtcars, method="lm", formula = my.formula, se = FALSE, color = "blue", fill = "blue") + stat_poly_eq (formula = my.formula, aes(label = paste(after_stat(eq.label), after_stat(adj.rr.label), after_stat(p.value.label), sep = "~~~")), parse = TRUE, size = 4, col = "black") + theme (panel.spacing = unit(0, "lines"), strip.background = element_blank(), plot.title = element_text(hjust = 0.5, color = "black", size = 14, face = "bold.italic"), strip.placement = "outside")print(p)
I'd assume blocking and adding random effects would be the same as for any linear model (+ Block OR + (1 | random.effect). However, I am not getting the code to work. Does anyone have any good ideas?
Here is an example of what I am talking about using mtcars. In this case I'll ask you to imagine that the vehicle weight is a random effect (I understand that it is likely not random effect but the example dataset doesn't include a good random effect. Here is the code I use to add the random effect and the regression line fails.
my.formula <- y ~ x + (1 | mtcars$wt)