当前位置:首页 > 谈天说地

R语言在散点图中添加lm线性回归公式的问题

34资源网2022-09-09523

1. 简单的线性回归

函数自带的例子(r 中键入?lm),lm(y ~ x)回归y=kx + b, lm( y ~ x -1 )省略b,不对截距进行估计:

require(graphics)

## annette dobson (1990) "an introduction to generalized linear models".
## page 9: plant weight data.
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2, 10, 20, labels = c("ctl","trt"))
weight <- c(ctl, trt)
lm.d9 <- lm(weight ~ group)
lm.d90 <- lm(weight ~ group - 1) # omitting intercept

anova(lm.d9)
summary(lm.d90)

opar <- par(mfrow = c(2,2), oma = c(0, 0, 1.1, 0))
plot(lm.d9, las = 1)      # residuals, fitted, ...
par(opar)

使用r中自带的mtcars数据,可以得到截距和斜率,也可以得到解释率r-square:

require(ggplot2)
library(dplyr) #加载dplyr包
library(ggpmisc) #加载ggpmisc包
library(ggpubr)
require(gridextra)
model=lm(mtcars$wt ~ mtcars$mpg)
model
## 输出:
call:
lm(formula = mtcars$wt ~ mtcars$mpg)

coefficients:
(intercept)   mtcars$mpg  
      6.047       -0.141
      ```
```handlebars
summary(model)

## 输出:
call:
lm(formula = mtcars$wt ~ mtcars$mpg)

residuals:
   min     1q median     3q    max 
-0.652 -0.349 -0.138  0.319  1.368 

coefficients:
            estimate std. error t value pr(>|t|)    
(intercept)   6.0473     0.3087   19.59  < 2e-16 ***
mtcars$mpg   -0.1409     0.0147   -9.56  1.3e-10 ***
---
signif. codes:  0 ‘***' 0.001 ‘**' 0.01 ‘*' 0.05 ‘.' 0.1 ‘ ' 1

residual standard error: 0.494 on 30 degrees of freedom
multiple r-squared:  0.753,	adjusted r-squared:  0.745 
f-statistic: 91.4 on 1 and 30 df,  p-value: 1.29e-10

提取回归r-square值:

通过summary提取:
## 上面的例子


## mtcars例子
model=lm(mtcars$wt ~ mtcars$mpg)
res=summary(model)
str(res) 
## 提取各个值:
res$r.squared
res$coefficients
res$adj.r.squared  ## df 矫正后的结果
res$coefficients[1,1]
res$coefficients[2,1]

使用默认的plot绘制回归散点:

plot(mtcars$mpg, mtcars$wt, pch=20,cex=2)
abline(model,col="red",lwd=2)

计算confidence interval(95%):

test=mtcars[c("mpg","wt")]
head(test)
colnames(test)=c("x","y")
model = lm(y ~ x, test)

test$predicted = predict(
  object = model,
  newdata = test)

test$ci = predict(
  object = model,
  newdata = test,
  se.fit = true
)$se.fit * qt(1 - (1-0.95)/2, nrow(test))

test$predicted = predict(
  object = model,
  newdata = test)

test$ci_u=test$predicted+test$ci
test$ci_l=test$predicted-test$ci
plot(mtcars$mpg, mtcars$wt, pch=20,cex=1) ##  have replicated x values
abline(model,col="red",lwd=2)
lines(x=test$x,y=test$ci_u,col="blue")
lines(x=test$x,y=test$ci_l,col="blue")

上面的图蓝线有点奇怪,简单绘制最初的plot:

plot(mtcars$mpg, mtcars$wt, pch=20,cex=1,type="b") ##  have replicated x values

实际上面的计算方法没问题,但是数据不合适,因为数据x含有重复值,所以要考虑这个。

2. 使用ggplot2展示

ggplot2例子:

p <- ggplot(df, aes(x=yreal, y=ypred)) +
  geom_point(color = "grey20",size = 1, alpha = 0.8)
#回归线
#添加回归曲线
p2 <- p + geom_smooth(formula = y ~ x, color = "red",
                      fill = "blue", method = "lm",se = t, level=0.95) +
  theme_bw() +
  stat_poly_eq(
    aes(label = paste(..eq.label.., ..adj.rr.label.., sep = '~~~')),
    formula = y ~ x,  parse = true,color="blue",
    size = 5, #公式字体大小
    label.x = 0.05,  #位置 ,0-1之间的比例
    label.y = 0.95) + 
  labs(title="test",x="real value (huang huaihai 1777)" , y="predicted value (correlation: 0.5029)")
p2

ggplot版本的手动计算:

require(ggplot2)
library(dplyr) #加载dplyr包
library(ggpmisc) #加载ggpmisc包
library(ggpubr)
require(gridextra)
ggplot(data=df, aes(x=yreal, y=ypred)) +
  geom_smooth(formula = y ~ x, color = "blue",
              fill = "grey10", method = "lm")  +
  geom_point() +
  stat_regline_equation(label.x=0.1, label.y=-1.5) +
  stat_cor(aes(label=..rr.label..), label.x=0.1, label.y=-2)

test=df
head(test)
colnames(test)=c("x","y")
model = lm(y ~ x, test)
test$predicted = predict(
  object = model,
  newdata = test)

test$ci = predict(
  object = model,
  newdata = test,
  se.fit = true
)$se.fit * qt(1 - (1-0.95)/2, nrow(test))

ggplot(test) +
  aes(x = x, y = y) +
  geom_point(size = 1,colour="grey40") +
  geom_smooth(formula =y ~ x,method = "lm",  fullrange = true, color = "black") +
  geom_line(aes(y = predicted + ci), color = "blue") + # upper
  geom_line(aes(y = predicted - ci), color = "red") + # lower
  theme_classic()

参考:
https://stackoverflow.com/questions/23519224/extract-r-square-value-with-r-in-linear-models (提取r2)
https://blog.csdn.net/leaningr/article/details/118971000 (提取r2等)
https://stackoverflow.com/questions/45742987/how-is-level-used-to-generate-the-confidence-interval-in-geom-smooth (添加lm线)
https://zhuanlan.zhihu.com/p/131604431 (知乎)

到此这篇关于r语言在散点图中添加lm线性回归公式的问题的文章就介绍到这了,更多相关r语言线性回归内容请搜索萬仟网以前的文章或继续浏览下面的相关文章希望大家以后多多支持萬仟网!

版权声明:34楼发布

本文链接:https://www.34l.com/post/21910.html

分享给朋友:

相关文章

用青出于蓝造句,学几句,或许对你有用

用青出于蓝造句,学几句,或许对你有用

1、青出于蓝而胜于蓝对于我们来说不会是不可能实现的梦想,只要我们足够的努力。…

一千元如何创业?一千元创业项目有吗?

一千元如何创业?一千元创业项目有吗?

一千元如何创业?有的人想用一千元创业,说实话,现实当中一千元根本创不了业,你买器材都不够,更别提创业了。当然,如果你在网络上面,那还是有可能创业的。因为现在网上有很多可以投资1000元左右创业的项目。下面,小编就给大家分享三个这样的创业项目…

木村久一:所谓天才人物指的就是具有毅力的人、勤奋的人、入迷的人和忘我的人

木村久一:所谓天才人物指的就是具有毅力的人、勤奋的人、入迷的人和忘我的人

木村久一:所谓天才人物指的就是具有毅力的人、勤奋的人、入迷的人和忘我的人。…

让长寿花开花有什么窍门?长寿花开花的几个条件分享

让长寿花开花有什么窍门?长寿花开花的几个条件分享

长寿花虽然说是一种多肉植物,但是它却和其他的很多多肉植物有很多不同的地方,长寿花由肥大、光亮的叶片形成的低矮株丛,终年翠绿。这种植物比较好看,也容易养,是送亲朋好友最好的礼物。马上要12月了,现在市面上卖花卉的很多。很多人不会养长寿花,尤其…

打代码赚钱的平台(免费打码赚钱软件)

打代码赚钱的平台(免费打码赚钱软件)

前言 开源项目作者:JackonYang 今天推荐的这个项目是「list-of-wechat-mini-program-list」,开源微信小程序列表的列表、有赚钱能力的小程序开源代码。 这个项目分为两部分,第一部分是开源微信小程序列表的…

网络加速器永久免费版(永久免费加速器推荐)

网络加速器永久免费版(永久免费加速器推荐)

WP-Rocket久负盛名,算是wordpress公认最强缓存插件之一。WP-Rocket插件开发于2013年,至今一直不断增加扩展新的功能,从最开始只支持静态文件压缩缓存,到现在整合了CDN加速、数据库冗余数据处理等。WP-Rocket这…