r - 如何在 R 中的绘图中添加一条最佳拟合线、方程、R^2 和 p 值?
问题描述
我有df1:
Stabr PCTPOVALL_2018 FIPS score1 score2 score3
3 AL 13.8 1001 26 3 10
4 AL 9.8 1003 20 1 5
7 AL 13.2 1009 21 6 7
8 AL 42.5 1011 60 5 10
9 AL 24.5 1013 65 3 10
10 AL 19.5 1015 42 2 8
我想密谋df1$PCTPOVALL_2018
反对score1
。我还想进行线性回归,看看这些变量之间是否存在显着关联。然后,我想将 p 值、R^2 和最佳拟合线绘制到该图上。我已经包含了我在油漆中制作的图像以供参考。我知道开始plot(df1$PCTPOVALL_2018,df1$score1,xlab="Pov",ylab="Score",main"Score vs Pov")
如何添加这些组件?我需要使用ggplot吗?
解决方案
您可以abline
根据调整后的线性模型的斜率和截距来绘制线,并用于text
将附加信息添加到绘图中(paste
用于将所有信息转换为字符串)。
#Save summary of the linear model
sum_lm<-summary(lm(score1~PCTPOVALL_2018, data = df1))
#Get coefficients
coef_lm<-sum_lm$coefficients
#Plot
plot(df1$PCTPOVALL_2018,
df1$score1,
xlab="Pov",
ylab="Score",
main= "Score vs Pov")
#Set the abline as the coefficients obtained by your linear model
abline(a = coef_lm[1,1],
b = coef_lm[2,1],
col = "lightblue",
lwd = 2)
#Add text to the plot in the x and y position (you might need to adjust these values according to your data)
#and add as labels a string that pastes all the info you wish to include. \n is interpreted as a line break.
text(x = max(df1$PCTPOVALL_2018)-20,
y = min(df1$score1)+10,
labels = paste0("R^2 = ",
#Round r.squared to 2 decimals
round(sum_lm$r.squared,2),
"\np-value = ",
#Round p.value of slope to 2 decimals
round(coef_lm[2,4],2),
"\ny = ",
#Round slope coefficient to 2 decimals
round(coef_lm[2,1],1),
"x + ",
#Round intercept coefficient to 2 decimals
round(coef_lm[1,1],2)),
pos = 4)
这是包含您的数据的结果图。
推荐阅读
- android - LibGDX - 缩放导致精灵在移动时有一条闪烁的线
- php - 在具有 HTML 的 PHP 标记中捕获到输入的意外异常
- translation - 新的 Microsoft 语音服务 WebSocket API 的端点是什么?
- python - 如何使用 for 循环或条件在 pandas 数据框的子集中创建多个回归模型(statsmodel)?
- tesseract - 在 lubuntu 18.04 上安装 tesseract 3.04
- spring-mvc - 从 java webapp 发送服务器端 POST
- wpf - WPF 中的图表控件
- excel - 设置两个不同的范围并执行代码
- javascript - 检查调查是否在过去 5 分钟内完成
- javascript - 具有一个指定参数的函数,其余参数可选