ggplot2点图+线性趋势+公式+$R^2$+p值

正文

先看效果。
ggplot2点图+线性趋势+公式+$R^2$+p值_第1张图片
R语言代码如下,

data("faithful")
library(ggplot2)
p <- ggplot(faithful,aes(x=eruptions,y=waiting)) + geom_point() + stat_smooth(method='lm',formula = y~x,colour='red')

model.lm<-lm(formula = waiting ~ eruptions, data = faithful)
#summary(model.lm)
#对于一元线性回归方程y=ax+b,Intercept是指的截距,x对应的是系数。

l <- list(a = as.numeric(format(coef(model.lm)[1], digits = 4)),
          b = as.numeric(format(coef(model.lm)[2], digits = 4)),
          r2 = format(summary(model.lm)$r.squared, digits = 4),
          p = format(summary(model.lm)$coefficients[2,4], digits = 4))

eq <- substitute(italic(y) == a + b %.% italic(x)~","~italic(R)^2~"="~r2~","~italic(P)~"="~p, l)

 p + geom_text(aes(x = 4, y = 50, label = as.character(as.expression(eq))), parse = TRUE)

参考文献

【1】https://www.jianshu.com/p/d6a5eb41ecec
【2】https://www.zhihu.com/question/54776335/answer/141091529
【3】https://rpkgs.datanovia.com/ggpubr/reference/stat_cor.html

你可能感兴趣的:(R,ggplot2)