xyz
xyz

Reputation: 133

Creating a Line of Best Fit in R

enter image description here

Hi, I was wondering if anyone could help me on how to complete function in R as I am totally new to this computer programming. So apologies if this seems like a silly question to this audience.

So I am currently trying to add a line of best fit onto my scatter graph but I'm not quite understanging how to do this. I've tried many functions like "abline" and "lm" but I'm not sure if I am using the right ideas or whether I am putting incorrect numbers into the functions.

I have cleared the workspace and just left my graph and previous workings so that it looks neater.

thanks in advance for the help.

Upvotes: 1

Views: 13573

Answers (1)

brian avery
brian avery

Reputation: 413

reproducible data example:

set.seed(2348907)
x <- rnorm(100)
y <- 2*(x+rnorm(100))

then this makes a linear model for the intercept and slope:

lmodel <- lm(y ~ x)

which now contains the intercept (Intercept term) and the slope (as the coefficient of the x variable in the model). Here is a summary of the model:

summary(lmodel)
Call:
lm(formula = y ~ x)

Residuals:
    Min      1Q  Median      3Q     Max 
-3.8412 -1.0767 -0.1808  1.2216  4.1540 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)   0.0454     0.1851   0.245    0.807    
x             2.1087     0.1814  11.627   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 1.848 on 98 degrees of freedom
Multiple R-squared:  0.5797,    Adjusted R-squared:  0.5754 
F-statistic: 135.2 on 1 and 98 DF,  p-value: < 2.2e-16

then make the plot using the coef() function to pull out the intercept and slope from the linear model:

plot(x,y)  # plots the points
abline(a=coef(lmodel)[1], b=coef(lmodel)[2])  # plots the line, a=intercept, b=slope 

enter image description here

personally, I prefer ggplot2 for such things, which would be like this:

library(ggplot2)
ggplot() + geom_point(aes(x,y)) + 
  geom_smooth(aes(x,y), method="lm", se=F)

enter image description here

Upvotes: 2

Related Questions