I am trying to replicate the beta distribution animation of Wikipedia in R.
Originally, I started with the following code
ggplot() +
xlim(0, 1) +
geom_function(fun = dbeta, args = list(shape1 = 5, shape2 = 5))
But I did not manage to use gganimate
to animate the plot based on the shape parameters.
Therefore I tried a second approach where I first generate the data and then plot it using geom_line()
(similar as in this post)
library(tidyverse)
library(gganimate)
# get beta PDF for specific parameters ------------------------------------
calc_beta <- function(alpha, beta){
X <- seq(0.01, 0.99, 0.01)
PDF <- dbeta(X, shape = alpha, shape2 = beta)
tibble(X, PDF)
}
# alpha and beta values ---------------------------------------------------
n <- 50
r <- exp(seq(log(0.1), log(5), length.out = n))
alpha <- c(rev(r), r, rep(5, 2*n), rev(r), r)
beta <- c(rep(5, 2*n), rev(r), r, rev(r), r)
# tibble with alpha, beta and PDF -----------------------------------------
dat <- tibble(alpha = alpha, beta = beta) %>%
mutate(time = 1:n()) %>%
group_by(time) %>%
mutate(plotdata = map2(alpha, beta, calc_beta)) %>%
unnest(plotdata)
# plot --------------------------------------------------------------------
p <- dat %>%
ggplot(aes(x = X, y = PDF)) +
geom_line() +
transition_time(time) +
coord_cartesian(ylim = c(0, 4)) +
annotate('text', x = 0.5, y = 4,
label = 'alpha = {round(alpha[as.integer(frame_time)], 2)}
beta = {round(beta[as.integer(frame_time)], 2)}') +
labs(title = 'alpha = {round(alpha[as.integer(frame_time)], 2)}
beta = {round(beta[as.integer(frame_time)], 2)}')
animate(p, nframes = 400, fps = 40)
Now I have 3 Qustions
- Is there a way to use
gganimate
to animate theargs
ofgeom_function
(first approach)? - Is there an easier solution then the second approach?
- Why does the animate labeling not work within the
annotate()
function but only within thelabs()
function?