 # How to overlay linear regression in ggplot2?

I have some data with headers INTERVAL and DURATION
I am new to R. I want to make a scatterplot and then overlay linear regression
please tell me what I am doing wrong

``````
detach(oldfaithful)
attach(oldfaithful)
n = length(DURATION)
ggplot(oldfaithful, mapping = aes(x = INTERVAL, y = DURATION)) +
geom_point(alpha=.5) +
labs(x="Interval between eruptions in minutes", y="duration of eruption in minutes")+
geom_abline(lm(INTERVAL~DURATION))

Error: `mapping` must be created by `aes()

#### System Information:
- RStudio Edition: Desktop
- RStudio Version: Version 1.4.1717
- OS Version: Windows 10
- R Version:``````

Use `geom_smooth()` instead, look at this example using a built-in dataset

``````library(ggplot2)

ggplot(faithful, mapping = aes(x = waiting, y = eruptions)) +
geom_point(alpha=.5) +
labs(x="Interval between eruptions in minutes", y="duration of eruption in minutes")+
geom_smooth(method = "lm")
#> `geom_smooth()` using formula 'y ~ x'
`````` Created on 2021-07-17 by the reprex package (v2.0.0)

1 Like

Thank you so much!
I finally got something to work but I will try your method in the future!

ggplot(oldfaithful, mapping = aes(x = DURATION, y = INTERVAL )) +
geom_point(alpha=.5, color="blue") +
labs(y="Interval between eruptions in minutes", x="duration of eruption in minutes") +
geom_abline(intercept = coef(fit), slope = coef(fit))

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.