How to add a line of best fit, equation, R^2, and p-value to a plot in R?

Viewed 1263

I have the 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

I would like to plot df1$PCTPOVALL_2018 against score1. I would also like to run a linear regression to see if there is a significant association between these variables. I would then like to plot the p-value, the R^2, and the line of best fit onto this graph. I have included an image that I made in paint for reference. I know to begin with plot(df1$PCTPOVALL_2018,df1$score1,xlab="Pov",ylab="Score",main"Score vs Pov")enter image description here

how do I add these components? Do I need to use ggplot?

1 Answers

You could use abline to draw the line according to the slope and intercept of the adjusted linear model and use text to add the additional information to the plot (using paste to convert all the information to a string).

#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)

Here is the resulting plot with your data.

linear regression plot

Related