library(ggplot2)
library(splines)
data(diamonds)
plot1 <- ggplot(data = diamonds,
mapping = aes(x = carat, y = price)) +
layer(geom = "point") +
theme_bw() +
theme(legend.key = element_blank())
plot1
## Fit model
lm1 <- lm(formula = price ~ bs(carat, df = NULL, knots = c(0.5,1,2,3,4), degree = 1),
data = diamonds)
## Create a data frame to hold prediction
newdat <- data.frame(carat = seq(from = min(diamonds$carat), to = max(diamonds$carat), by = 0.01))
## Predict
newdat$price <- predict(lm1, newdata = newdat)
## Plot the previous plot with a regression line
plot1 + layer(geom = "line", data = newdat, color = "red")