Created
December 15, 2020 18:00
-
-
Save maxdrohde/1878ab6655ec264693ac643e16b2a3ec to your computer and use it in GitHub Desktop.
Animations for Unif(0,1) estimators of central tendency
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
library(tidyverse) | |
library(gganimate) | |
sample_size <- seq(5, 30, by=5) | |
create_data <- function(sample_size){ | |
tibble(ss=sample_size, n=1:1e6, x=map(n, ~runif(sample_size))) %>% | |
mutate(mean = map_dbl(x, mean), | |
median = map_dbl(x, median), | |
range = map_dbl(x, ~(max(.x) - min(.x))/2)) %>% | |
pivot_longer(cols=mean:range) %>% | |
select(-x) | |
} | |
df <- map_dfr(sample_size, ~create_data(.x)) | |
anim <- | |
df %>% | |
ggplot(aes(x=value, fill=name, color=name)) + | |
geom_density(alpha=0.3) + | |
scale_fill_manual(name = "Estimator", | |
labels = c("Mean", "Median", "Midrange"), | |
values = c("#1b9e77", "#d95f02", "#7570b3")) + | |
scale_color_manual(name = "Estimator", | |
labels = c("Mean", "Median", "Midrange"), | |
values = c("#1b9e77", "#d95f02", "#7570b3")) + | |
labs(subtitle = "Sample Size: {closest_state}", | |
title = "Estimators of central tendency for Unif(0,1)", | |
x= "x", | |
y= "Probability Density (KDE)", | |
caption = "Distributions estimated by Monte Carlo simulation") + | |
cowplot::theme_cowplot(font_family = "Source Sans Pro", | |
font_size = 10) + | |
theme(plot.title = element_text(size=10), | |
legend.position = c(0.8,0.8)) + | |
transition_states(ss, state_length = 1, transition_length = 2) + | |
ease_aes('quartic-in-out') | |
# Render animation | |
out <- animate(anim, | |
duration=10, | |
fps=60, | |
height = 3, | |
width = 4, | |
units = "in", | |
res = 300, | |
renderer = ffmpeg_renderer()) | |
# Save to mp4 | |
anim_save(animation = out, filename = "unif_center_anim.mp4") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment