Skip to content

Instantly share code, notes, and snippets.

@tjmahr
Forked from noamross/mgcv-posterior-animate.R
Last active September 4, 2018 18:01
Show Gist options
  • Save tjmahr/201c76e59f325305f84a5d8d6ebdbabe to your computer and use it in GitHub Desktop.
Save tjmahr/201c76e59f325305f84a5d8d6ebdbabe to your computer and use it in GitHub Desktop.
Animating smoothing uncertainty in a GAM
# devtools::install_github("thomasp85/transformr")
# devtools::install_github("thomasp85/gganimate")
library(tidyverse)
library(gganimate)
library(rstanarm)
theme_set(theme_grey())
# Get the mpg value to predict over
newdat <- data.frame(
mpg = seq(min(mtcars$mpg), max(mtcars$mpg), length.out = 100))
m <- stan_gamm4(
hp ~ s(mpg),
data = mtcars,
chains = 1,
iter = 2000)
demo_lines <- tidybayes::add_fitted_draws(newdat, m, n = 20)
interval <- tidybayes::add_fitted_draws(newdat, m) %>%
tidybayes::median_qi()
# Plot with animation!
ggplot(demo_lines, aes(x = mpg)) +
geom_ribbon(
aes(ymin = .lower, ymax = .upper),
data = interval,
fill = "lightgrey",
col = NA) +
geom_point(aes(y = hp), data = mtcars) +
geom_line(
aes(y = .value),
data = demo_lines,
col = "blue") +
transition_states(.draw, 1, 1)
@tjmahr
Copy link
Author

tjmahr commented Sep 4, 2018

file20d84c3e7b21

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment