# Scatter plot with regression line or curve in R

## Scatter plot based on a model

You can create a scatter plot based on a theoretical model and add it to the plot with the `lines` function. Consider the example of the following block of code as illustration.

``````# Data. Model: Y = X ^ 2
set.seed(54)
x <- seq(0, 10, by = 0.05)
y <- x ^ 2 + rnorm(length(x), sd = 20)

# Scatter plot and underlying model
plot(x, y, pch = 16)
lines(x, x ^ 2, col = 2, lwd = 3)

# Text
text(2, 70, expression(Y == X ^ 2))`````` ## Scatter plot with linear regression You can add a regression line to a scatter plot passing a `lm` object to the `abline` function. Recall that `coef` returns the coefficients of an estimated linear model.

``````# Data. Model: Y = X ^ 2
set.seed(54)
x <- seq(0, 10, by = 0.05)
y <- x ^ 2 + rnorm(length(x), sd = 20)

# Scatter plot and linear regression line
plot(x, y, pch = 16)
abline(lm(y ~ x), col = 4, lwd = 3)

# Text
coef <- round(coef(lm(y ~ x)), 2)
text(2, 70,  paste("Y = ", coef, "+", coef, "x"))``````

## Scatter plot with LOWESS regression curve

The LOWESS smoother uses locally-weighted polynomial regression. This non-parametric regression can be estimated with `lowess` function.

``````# Data. Model: Y = X ^ 2
set.seed(54)
x <- seq(0, 10, by = 0.05)
y <- x ^ 2 + rnorm(length(x), sd = 20)

# Scatter plot and LOWESS regression curve
plot(x, y, pch = 16)
lines(lowess(x, y), col = 3, lwd = 3)`````` 