r - 如何将 R^2 和回归值添加到 ggplot2 中的多因素设计
问题描述
我有一个 2 x 2 的设计。我需要为每个因素添加 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 值处提取模型值并使用它。
如果有帮助的话,很高兴分享其中一个,但是有很多时间用于发布图,我会回到手动文本放置,就像这样。
推荐阅读
- windows - 尽管在命令行中输入了值,但带有强制参数的 powershell 脚本一直提示我输入值
- java - Java - 使用扫描仪读取文本文件并存储它,给我空的 ArrayList。使用分隔符拆分单词
- database - Best approach for Cassandra Partitioning
- ios - 您可以拥有多个 iOS 应用程序使用相同的 Firebase 后端吗?
- ssh - OpenSSH 服务器不为来自不同 IP 的客户端提供相同的身份验证方法
- oracle - 检查约束以强制执行参照完整性?
- android - 更新应用程序时,哪些应用程序更改会导致重新安装/替换?
- python - 有限的数据集:离线增强与具有更多时期的在线增强
- javascript - Mongoose search using regex and ignoring special characters
- java - 如何使 POST-emission 出现延迟?