Last active
January 10, 2019 19:11
-
-
Save ajstewartlang/47c668bf0fff01322442c568a7e08f41 to your computer and use it in GitHub Desktop.
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
# From @nnstats on Twitter | |
# Imagine a hockey game where we know that Team A scores exactly 1 goal for sure and Team B takes 20 shots, | |
# each with a 5.5% chance of going in. | |
# Which team would you rather be? | |
# (nothing additional happens if you tie.) | |
library(tidyverse) | |
library(gganimate) | |
set.seed(1234) | |
team_b_goals <- NULL | |
for(i in 1:10000) { | |
score <- sum(sample(c(1, 0), size = 20, replace = TRUE, prob = c(0.055, 1-.055))) | |
team_b_goals <- c(team_b_goals, score)} | |
team_a_goals <- rep(1, 10000) | |
all_games <- as_tibble(cbind(team_a_goals, team_b_goals)) | |
# Calculate cumulative sum of each Team's goals | |
all_games <- all_games %>% | |
mutate(team_a_wins = team_a_goals > team_b_goals, | |
team_b_wins = team_b_goals > team_a_goals) | |
all_games$game_number <- seq(1:10000) | |
all_games$team_a_wins <- cumsum(all_games$team_a_wins) | |
all_games$team_b_wins <- cumsum(all_games$team_b_wins) | |
small_data <- tibble(c(all_games$team_a_wins, all_games$team_b_wins), | |
c(rep("Team_A", 10000), rep("Team_B", 10000)), | |
c(seq(1:10000), seq(1:10000))) | |
colnames(small_data) <- c("Points", "Team", "Game") | |
small_data %>% # add filter(Game < 1001) %>% to plot the first 1000 games only | |
ggplot(aes(x = Points, y = Game, group = Team, colour = Team)) + | |
geom_point() + | |
geom_line(size = 2) + | |
coord_flip() + | |
transition_reveal(Game) + | |
shadow_mark(past = TRUE) + | |
labs(title = "Wins of Team A vs. Team B", | |
x = "Running total of wins", | |
y = "Game number") + | |
theme(text = element_text(size = 15)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment