如何在R中使用ggplot2创建的图表显示回归截距?
要在ggplot2创建的图表中显示模型的回归截距,我们可以按照以下步骤操作:
- 首先,创建数据框。
- 使用ggplot2的annotate函数创建散点图,并在图上显示回归截距。
- 检查回归截距。
创建数据框
让我们创建一个如下所示的数据框:
x<-sample(1:100,25) y<-sample(1:100,25) df<-data.frame(x,y) df
执行上述脚本后,将生成以下输出(由于随机化,此输出在您的系统上会有所不同):
x y 1 55 8 2 8 22 3 87 66 4 95 49 5 68 57 6 66 31 7 21 13 8 27 77 9 45 25 10 94 46 11 77 7 12 93 50 13 7 58 14 13 82 15 83 88 16 17 39 17 43 23 18 11 35 19 39 24 20 50 40 21 37 99 22 18 78 23 30 42 24 86 17 25 71 16
创建带有回归截距的散点图
创建带有回归线和在图上显示的模型截距的散点图:
x<-sample(1:100,25)
y<-sample(1:100,25)
df<-data.frame(x,y)
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()+stat_smooth(method="lm",se=F)+annotate("text",x=2
0,y=95,label=(paste0("Intercept==",coef(lm(df$y~df$x))[1])),parse=TRUE)
`geom_smooth()` using formula 'y ~ x'输出

检查模型的截距
使用coeff函数查找模型的截距,并检查它是否与图中显示的截距匹配:
x<-sample(1:100,25) y<-sample(1:100,25) df<-data.frame(x,y) coef(lm(df$y~df$x))[1]
输出
(Intercept) 47.29387
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP