Created
October 5, 2018 13:10
-
-
Save ajstewartlang/5485384d93911a390652d9bb4d5cea24 to your computer and use it in GitHub Desktop.
moving averages animation
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) | |
data <- NULL | |
sample <- NULL | |
d <- NULL | |
for (i in (1:100)) { | |
set.seed(i+1234) | |
a <- rnorm(25, 1000, 50) | |
b <- rep(i, 25) | |
c <- mean(a) | |
c_1 <- rep(c, 25) | |
if (is.null(d)) {d <- c_1} | |
else {d <- mean(c(c_1, data$sample_mean))} | |
sample <- as.data.frame(cbind(b, a, c, d)) | |
colnames(sample) <- c("sample", "DV", "sample_mean", "running_mean") | |
data <- rbind(sample, data) | |
} | |
ggplot(data, aes(x = sample, y = running_mean)) + geom_point(size = 5) + | |
geom_hline(yintercept = 1000, colour = "blue") + | |
scale_y_continuous(breaks = 996:1004) + | |
labs(x = "Sample Number", y = "Moving Average", | |
title = "Moving average gets closer to the population \nmean (blue line) as sampling increases.") + | |
theme_minimal() + | |
theme(text = element_text(size = 15)) + | |
transition_time(sample) + shadow_mark(size = 5, colour = "grey") | |
ggplot(data) + | |
geom_vline(xintercept = 1000, colour="blue", size=2) + | |
geom_vline(aes(xintercept = running_mean, colour = "red", size = 1.5)) + | |
guides(colour = FALSE, size = FALSE) + coord_flip() + | |
scale_x_continuous(breaks = 996:1004) + | |
labs(x = "Estimtaed population mean", | |
title = "Estimated mean gets closer to the true \nmean (blue line) as sampling increases up to \nand including sample number {frame_time}.") + | |
theme_minimal() + | |
theme(text = element_text(size = 14)) + | |
transition_time(sample) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment