How to make a simple "animation" by redrawing a graph

Viewed 76

The code below generates what appears almost as an animation in R studio because it renders 100 plots, each plot has slightly more data than then previous plot.

################################################################################
# Visualise probability of heads tending towards 0.5 as more tests performed

# Number of tests to run
tests <-  100

# duration to run for in seconds
durationSeconds <- 10

ht <- sample(c('heads', 'tails'), tests, replace=TRUE)
total <- vector()
for (i in 1:tests) {
  headsAtI <- length(which(ht[1:i] == 'heads'))
  total[i] <- headsAtI/i
  Sys.sleep(durationSeconds/tests)
  plot(total, type='l')
  abline(h = 0.5, col='blue')
}

This works but has some serious issues:

  1. 100 plots are created, I guess ideally one should be created and re-used
  2. If I change the value of 'tests' to be say 10,000, R Studio will hang or crash

What is the proper way to do this in R Studio?

I realise that I can just draw a single plot at the end, with all the "results", but I want to achieve the "animation" effect.

enter image description here

1 Answers

Have you considered gganimate ?

library(dplyr)
library(gganimate)
library(ggplot2)

tests <-  100
ht <- sample(c('heads', 'tails'), tests, replace=TRUE)

p <- data.frame(ht) %>%
       mutate(headsAtI = cumsum(ht == 'heads'),
              index = row_number(),
              total = headsAtI/index) %>%
       ggplot() + aes(index, total) + geom_line() + 
       geom_hline(yintercept = 0.5, color = 'blue') + 
       transition_reveal(index)
p

enter image description here

Related