在图形上添加回归线方程和 R^2 [英] Add regression line equation and R^2 on graph
本文介绍了在图形上添加回归线方程和 R^2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何在 ggplot
上添加回归线方程和 R^2.我的代码是:
库(ggplot2)df <- data.frame(x = c(1:100))df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)p <- ggplot(data = df, aes(x = x, y = y)) +geom_smooth(method = "lm", se=FALSE, color="black", 公式 = y ~ x) +geom_point()p
任何帮助将不胜感激.
解决方案
这里有一个解决方案
# 得到方程和 R 平方作为字符串# 来源:https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMAlm_eqn <- 函数(df){m <- lm(y ~ x, df);eq <-substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,列表(a = 格式(无名(系数(m)[1]),数字 = 2),b = 格式(unname(coef(m)[2]), 数字 = 2),r2 = 格式(汇总(m)$r.squared,数字 = 3)))as.character(as.expression(eq));}p1 <- p + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)
编辑.我从我选择这段代码的地方找出了来源.这是 link 到 ggplot2 谷歌群组中的原始帖子>
I wonder how to add regression line equation and R^2 on the ggplot
. My code is:
library(ggplot2)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
geom_point()
p
Any help will be highly appreciated.
解决方案
Here is one solution
# GET EQUATION AND R-SQUARED AS STRING
# SOURCE: https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMA
lm_eqn <- function(df){
m <- lm(y ~ x, df);
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(unname(coef(m)[1]), digits = 2),
b = format(unname(coef(m)[2]), digits = 2),
r2 = format(summary(m)$r.squared, digits = 3)))
as.character(as.expression(eq));
}
p1 <- p + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)
EDIT. I figured out the source from where I picked this code. Here is the link to the original post in the ggplot2 google groups
这篇关于在图形上添加回归线方程和 R^2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文