Skip to content

Instantly share code, notes, and snippets.

@grantmcdermott
Last active August 12, 2020 22:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grantmcdermott/be59c2510670a172436c2d4274aa0b10 to your computer and use it in GitHub Desktop.
Save grantmcdermott/be59c2510670a172436c2d4274aa0b10 to your computer and use it in GitHub Desktop.
Example using broom::augment(interval = '..') to visualize out of sample predictions
## 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