2017-03-31 59 views
0

我一直在寻找这一段时间,但无法获得解决方案。如何格式化和移动ggplot中每个组的多元回归方程?

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倍的值,但它们是在同一个地方,我应该怎么格式化显示这些方程的地方吗?

My current plot

非常感谢所有帮助!!!!

+0

什么是您预期的输出? – mtoto

+0

[ggplot2:在图上添加回归直线方程和R2]可能重复(http://stackoverflow.com/questions/7549694/ggplot2-adding-regression-line-equation-and-r2-on-graph) – Vlo

+0

@mtoto我只是更新了我的情节,这些方程式显示在同一个地方,我怎样才能让它们移动以便我们看到? –

回答

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

+0

非常感谢!这真的有帮助! –

+0

请问如何修改这些方程的位置? –

+0

使用'stat_poly_eq'中的选项'label.x'和'label.y'。例如,根据上图中的比例,如果我想将方程推到右上角,我可以修改代码:'stat_poly_eq(formula = y〜x,aes(label = paste(.. eq。 label ..,..rr.label ..,sep =“~~~”)),parse = TRUE,label.x = 60,label.y = 70)'。这应该改变方程的位置 – Kay

相关问题