今天给大家分享三种在ggplot2包画的图形上添加拟合的线性回归方程和R^2的值的方法。
1 解决方案1
代码语言:javascript复制library(ggplot2)
set.seed(1234)
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
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)
p1
运行结果,如图1所示。
2 解决方案2,借用了ggpmisc包。
代码语言:javascript复制library(ggplot2)
library(ggpmisc)
set.seed(1234)
df <- data.frame(x = c(1:100))
df$y <- 2 3 * df$x rnorm(100, sd = 40)
my.formula <- y ~ x
p <- ggplot(data = df, aes(x = x, y = y))
geom_smooth(method = "lm", se=FALSE, color="black", formula = my.formula)
stat_poly_eq(formula = my.formula,
aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
parse = TRUE)
geom_point()
p
运行结果,如图2所示。
3 解决方案3,借用了ggpurb包。
代码语言:javascript复制library(ggplot2)
library(ggpubr)
set.seed(1234)
df <- data.frame(x = c(1:100))
df$y <- 2 3 * df$x rnorm(100, sd = 40)
ggscatter(df, x = "x", y = "y", add = "reg.line")
stat_cor(label.y = 300,
aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~")))
stat_regline_equation(label.y = 280)
运行结果,如图3所示。