繁体   English   中英

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

[英]How to add R^2 and regression values to multi-factorial design in ggplot2

我有两个x两个设计。 我需要为每个因子添加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)

在此处输入图片说明

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

eq添加一个新列,以使用geom_text(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) 

也许更优雅,更灵活的解决方案是提取模型的截距并将该值设置为每个方程的y位置。 或者,您可以提取给定x值的模型值并使用该值。

乐于分享其中的一种(如果有帮助的话),但是我花了很多时间来进行出版物策划,就像这样,我还是回到了手工放置文本的位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM