首页 > 解决方案 > 如何在 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吗?

标签: rdataframeggplot2graph

解决方案


您可以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)

这是包含您的数据的结果图。

线性回归图


推荐阅读