ggplot2 overlying piece-wise linear model

References

Load packages

library(ggplot2)
library(splines)

Load dataset

data(diamonds)

Scatter plot

plot1 <- ggplot(data = diamonds,
                mapping = aes(x = carat, y = price)) +
         layer(geom = "point") +
         theme_bw() +
         theme(legend.key = element_blank())
plot1

plot of chunk unnamed-chunk-4

Piece-wise regression

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

plot of chunk unnamed-chunk-5