首先模拟一份数据集
df<-data.frame(x = c(1:100))
df$y<- 2 + 3 * df$x + rnorm(100, sd = 40)
head(df)
ggplot2基本的散点图并添加拟合曲线
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
如果要显示95%置信区间,可以将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
添加拟合方程和R2
这里是自定义了一个函数, 直接用就可以了
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
参考:https://cloud.tencent.com/developer/article/1854758
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!