0

I have been searching this for a while but can't get a solution.

This is the data I have 
Display     Frustration  Neck Angle
1 Microscope          55 40.77672
2 Microscope          70 53.74905
3 Loupe               10 52.41799
4 Loupe               5  62.36514
5 Video               25 49.83489
6 Video               10 68.19686 
my current code

lm_eqn <- function(df){
 m <- lm(Neck ~ Frustration, df);
  eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2, 
                   list(a = format(coef(m)[1], digits = 2), 
                        b = format(coef(m)[2], digits = 2), 
                        r2 = format(summary(m)$r.squared, digits = 3)))
  as.character(as.expression(eq));                 
}
eq <- ddply(df.frus,"Display",lm_eqn)
p<- ggplot(df.frus,aes(x=Frustration,y=Neck,col=Display))+geom_jitter(width=0.5)+geom_smooth(method="lm",se=FALSE)
p+geom_text(data=eq,aes(x = 30, y = 80,label=V1), parse = TRUE)

Now I am able to generate regression lines and r^2 values for each group, but they are in the same place, how should I format the place of showing these equations?

My current plot

Really appreciate any help!!!!

Ives Shi
  • 31
  • 1
  • 5
  • What is your expected output? – mtoto Mar 31 '17 at 18:42
  • Possible duplicate of [ggplot2: Adding Regression Line Equation and R2 on graph](http://stackoverflow.com/questions/7549694/ggplot2-adding-regression-line-equation-and-r2-on-graph) – Vlo Mar 31 '17 at 18:57
  • @mtoto I just updated the plot I have, these equations are showing up at the same place, how can I make move them so that we can see? – Ives Shi Mar 31 '17 at 19:35

1 Answers1

2

You can use the ggpmisc package.

library(ggpmisc)
ggplot(df.frus,aes(x=Frustration,y=Neck,col=Display))+geom_jitter(width=0.5)+
stat_poly_eq(formula = y~x, aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")), parse = TRUE)

enter image description here

Kay
  • 2,057
  • 3
  • 20
  • 29
  • May I ask how to modify the position of these equations? – Ives Shi Apr 03 '17 at 17:18
  • Use the options `label.x` and `label.y` in `stat_poly_eq`. For instance based on the scale in the above graph, if I want to push the equations to the top right corner, I can modify the code as: `stat_poly_eq(formula = y~x, aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")), parse = TRUE, label.x = 60, label.y = 70)`. This should change the position of the equations – Kay Apr 04 '17 at 05:30