如何将R^2和回归值添加到ggplot2中的多因子设计中

如何将R^2和回归值添加到ggplot2中的多因子设计中,r,ggplot2,linear-regression,R,Ggplot2,Linear Regression,我有一个二乘二的设计。我需要为每个因子添加R2和回归值——图上用颜色编码。我曾经部分地修改过这个问题的代码,但是我仍然只得到一条回归线。此外,回归方程打印不清楚。我需要四个颜色编码的回归方程 fertilizer <- c("N","N","N","N","N","N","N","N","N","N","N","N","P","P","P","P","P","P","P","P","P","P","P","P","N","N","N","N","N","N","N","N","N","N"

我有一个二乘二的设计。我需要为每个因子添加R2和回归值——图上用颜色编码。我曾经部分地修改过这个问题的代码,但是我仍然只得到一条回归线。此外,回归方程打印不清楚。我需要四个颜色编码的回归方程

fertilizer <- c("N","N","N","N","N","N","N","N","N","N","N","N","P","P","P","P","P","P","P","P","P","P","P","P","N","N","N","N","N","N","N","N","N","N","N","N","P","P","P","P","P","P","P","P","P","P","P","P")

    level <- c("low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","high","low","low","high","low")

    growth <- c(0,0,1,2,90,5,2,5,8,55,1,90,2,4,66,80,1,90,2,33,56,70,99,100,66,80,1,90,2,33,0,0,1,2,90,5,2,2,5,8,55,1,90,2,4,66,0,0)


    repro <- c(1,90,2,4,66,80,1,90,2,33,56,70,99,100,66,80,1,90,2,33,0,0,1,2,90,5,2,2,5,8,55,1,90,2,4,66,0,0,0,0,1,2,90,5,2,5,8,55)

    df <- data.frame(fertilizer, level, growth, repro)


    lm_eqn = function(df){
      m = lm(growth ~ repro, 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,.(fertlizer + level),lm_eqn)

ggplot(df, aes(x=growth, y=repro, color = fertilizer)) +  theme_bw() + geom_point(aes(colour = factor(fertilizer)), size = 0.1,alpha = 0.3) +
  geom_smooth(method='lm',se=FALSE, aes(colour = factor(fertilizer)), formula = y ~ x)+ scale_color_manual(values=c("#E69F00", "#1B9E77")) +
  facet_wrap(.~level, scales = "free") + theme(legend.position = "none") + theme(aspect.ratio = 1.75/1) + geom_text(data=eq,aes(x = 50, y = 25,label=V1), parse = TRUE, inherit.aes=FALSE, size = 2)

furture有很多方法可以实现非重叠,这是非常基本的,也是非常手动的

eq
中添加一个新列,用于映射
geom_文本(aes(y=y_pos))
,而不是当前使用的常量

eq$y_pos <- c(24, 36, 8, 24)

ggplot(df, aes(x=growth, y=repro, color = fertilizer)) +
  geom_smooth(method='lm',se=FALSE, aes(colour = factor(fertilizer)), formula = y ~ x) +
  geom_point(aes(colour = factor(fertilizer)), size = 0.1,alpha = 0.3) +
# change here 
  geom_text(data=eq,aes(x = 50, y = y_pos, label=V1), parse = TRUE, inherit.aes=FALSE, size = 2) +
# ----
  scale_color_manual(values=c("#E69F00", "#1B9E77")) +
  facet_wrap(.~level, scales = "free") +
  theme_bw() + 
  theme(legend.position = "none",
        aspect.ratio = 1.75/1) 

eq$y\u pos我想您在
ddply()
中有语法错误,应该是
eq,那么如何使它们不重叠呢?