0

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,

1 Answer 1

1

I'm pretty sure that setting adjusting stat_poly_eq() with the geom argument will get what you want. Doing so will center the equations, leaving the left half of each clipped, so we use hjust = 0 to left-adjust the equations. Finally, depending on your specific data, the equations may be overlapping each other, so we use the position argument to have ggplot attempt to separate them.

This adjusted call should get you started, I hope:

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, geom = "text", # or 'label' hjust = 0, # left-adjust equations position = position_dodge(), # in case equations now overlap aes(x = x , y = ymax + 1, label = paste(..eq.label.., ..rr.label.., sep = "~~~")), parse = TRUE) + geom_point() p 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.