# Three estimates with different complexity
fit_linear <- lm(y ~ x, data=dat)
fit_poly5 <- lm(y ~ poly(x, 5), data=dat)
fit_poly15 <- lm(y ~ poly(x, 15), data=dat)
preds <- data.frame(
x = x_grid,
true = f_vals,
linear = predict(fit_linear, newdata=data.frame(x=x_grid)),
poly5 = predict(fit_poly5, newdata=data.frame(x=x_grid)),
poly15 = predict(fit_poly15, newdata=data.frame(x=x_grid))
)
ggplot(dat, aes(x, y)) +
geom_point(alpha=0.3, size=1.5, colour="#999") +
geom_line(data=preds, aes(x, true), colour="#e74c3c", linewidth=1.2, linetype="dashed") +
geom_line(data=preds, aes(x, linear), colour="#2980b9", linewidth=1) +
geom_line(data=preds, aes(x, poly5), colour="#27ae60", linewidth=1) +
geom_line(data=preds, aes(x, poly15), colour="#8e44ad", linewidth=1) +
labs(title="Three estimates of f",
subtitle="Red dashed = true f | Blue = linear | Green = poly(5) | Purple = poly(15)",
x="X", y="Y") +
theme_minimal()