Example using broom::augment(interval = '..') to visualize out of sample predictions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Context: https://twitter.com/grant_mcdermott/status/1293673082352099328 | |
library(broom) ## remotes::install_github('tidymodels/broom') | |
library(ggplot2) | |
## gen fake data | |
set.seed(123) | |
x = sort(runif(100, min = 0, max = 5)) | |
y = x^2 + rnorm(100) | |
dat = data.frame(x, y) | |
## estimate model on training sample (first 30 obs *only*) | |
est = lm(y ~ I(x^2), data = dat[1:30, ]) | |
## add predictions (with interval) to data with augment() | |
dat = augment(est, newdata = dat, interval = 'prediction') | |
## Plot | |
ggplot(dat, aes(x, y)) + | |
geom_point() + | |
geom_line(aes(y = .fitted)) + | |
geom_ribbon(aes(ymin = .conf.low, ymax = .conf.high), alpha = 0.2) + | |
geom_vline(xintercept = x[30], lty = 2) + | |
annotate('text', x = x[30], y = max(y), label = 'Training ', hjust = 1) + | |
annotate('text', x = x[30], y = max(y), label = ' Forecast', hjust = 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment