I would like to add the regression line and R^2 to my ggplot. I am fitting the regression line to different categories and for each category I am getting a unique equation. I'd like to set the position of equations for each category manually. i.e. Finding the max expression of y for each group and printing the equation at ymax + 1.
Here is my code:
library(ggpmisc) df <- data.frame(x = c(1:100)) df$y <- 20 * c(0, 1) + 3 * df$x + rnorm(100, sd = 40) df$group <- factor(rep(c("A", "B"), 50)) df <- df %>% group_by(group) %>% mutate(ymax = max(y)) my.formula <- y ~ x df %>% group_by(group) %>% do(tidy(lm(y ~ x, data = .))) p <- ggplot(data = df, aes(x = x, y = y, colour = group)) + geom_smooth(method = "lm", se=FALSE, formula = my.formula) + stat_poly_eq(formula = my.formula, aes(x = x , y = ymax + 1, label = paste(..eq.label.., ..rr.label.., sep = "~~~")), parse = TRUE) + geom_point() p Any suggestion how to do this?
Also is there any way I can only print the slope of the equation. (remove the intercept from plot)?
Thanks,