如何格式化并移动ggplot中每个组的多个回归方程?

时间:2017-03-31 18:38:31

标签: r ggplot2 regression

我已经搜索了一段时间但无法得到解决方案。

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)

现在我能够为每个组生成回归线和r ^ 2值,但它们在同一个地方,我应该如何格式化显示这些方程的位置?

Collections.sort

非常感谢任何帮助!!!!

1 个答案:

答案 0 :(得分:1)

您可以使用ggpmisc包。

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