Skip to content

Instantly share code, notes, and snippets.

@JoFrhwld
Created October 23, 2017 13:19
Show Gist options
  • Save JoFrhwld/060f0f5b8ff4af0e95021b2ee0a754f0 to your computer and use it in GitHub Desktop.
Save JoFrhwld/060f0f5b8ff4af0e95021b2ee0a754f0 to your computer and use it in GitHub Desktop.
library(tweenr)
library(gganimate)
library(ggplot2)
library(tidyverse)
#' define the 4 states
state1 <- data_frame(mean = 0,
sd = 1)
state2 <- data_frame(mean = 0,
sd = 3)
state3 <- data_frame(mean = 0,
sd = 0.5)
state4 <- data_frame(mean = 0,
sd = 1)
#' tweening the parameters
param_list <- list(state1, state2, state3, state4)
param_tween <- tween_states(param_list, tweenlength = 10, statelength = 2, ease = "cubic-in-out", nframe = 200)
#' function to generate the densituy distributions
make_dist <- function(df){
out <- data_frame(x = seq(-8, 9, length = 200),
y = dnorm(x, mean = df$mean, sd = df$sd),
mean = df$mean,
sd = df$sd)
return(out)
}
#' generating the tweened distributiobs
dist_tween <- param_tween %>%
group_by(.frame)%>%
summarize(mean = mean(mean),
sd = mean(sd)) %>%
group_by(.frame)%>%
nest() %>%
mutate(dist = map(data, make_dist))%>%
unnest(dist)
#' making the labels
dist_tween %>%
group_by(.frame)%>%
summarise(mean = max(mean),
sd = max(sd)) %>%
mutate(mulab = paste0("mu==", round(mean, digits = 2)),
siglab = paste0("sigma==", round(sd, digits = 2)))->label_states
#' the animation plot
sigma_anim <- dist_tween %>%
ggplot(aes(x, y)) +
geom_ribbon(aes(frame = .frame, ymin = 0, ymax = y),color = "#2171b5", size = 3, fill = "#bdd7e7") +
#geom_point(aes(frame = .frame))+
geom_text(data = label_states, aes(label = mulab, x=mean, y = .1, frame = .frame), parse = T)+
geom_text(data = label_states, aes(label = siglab, x=mean, y = 0.05, frame = .frame), parse = T)+
theme_minimal()
# Set up options and animate
animation::ani.options(interval = 1/30, ani.width = 800/1.5, ani.height = 500/1.5)
gganimate(sigma_anim, filename = "sigma_anim2.gif", title_frame = F)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment