最近在画散点图的时候使用lm函数进行线性回归拟合之后,想将拟合的方程与R2加入到绘制的图片中。在百度中翻了半天,终于在一个外国网站上找到了方法。下面我把这个方法介绍给大家。
参考链接是
https://stackoverflow.com/questions/7549694/add-regression-line-equation-and-r2-on-graph
df<-data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
head(df)
library(ggplot2)
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "lm", se=FALSE,
color="black", formula = y ~ x) +
geom_point()
p
题外话:有读者在公众号留言说R语言做出来的图有锯齿,应该是在Rstudio那个图形显示界面就是这个,如果导出图片后就会变得清楚了,这里为什么在Rstudio的图形显示界面会不清楚 我也不知道
se
参数的FALSE
改为TRUE
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "lm", se=TRUE,
color="black", formula = y ~ x) +
geom_point()+
theme_bw()
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
加载R包,模拟数据集
library(ggplot2)
library(ggpmisc)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
head(df)
这里添加拟合方程用到的是 stat_poly_eq()
这个函数
library(ggplot2)
library(ggpmisc)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
head(df)
my.formula <- y ~ x
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()
代码
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(size=4,
alpha=0.7,
color="#fe654c")+
coord_cartesian(ylim = c(0,320),
xlim = c(0,105))+
scale_y_continuous(breaks = c(0,100,200,300))+
scale_x_continuous(breaks = c(0,25,50,75,100,105))+#x轴比上个图多个105
theme_bw()+
geom_smooth(method = "lm",
color="#558ebd",
fill="lightgray",
alpha=.7,
size=0.8,se=T,
formula = y~x)+
theme(panel.grid = element_blank())
最终出图