Skip to content

Instantly share code, notes, and snippets.

@thomaspinder
Created January 15, 2019 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomaspinder/4fda5d4ae642a804f4d7a549e627bed7 to your computer and use it in GitHub Desktop.
Save thomaspinder/4fda5d4ae642a804f4d7a549e627bed7 to your computer and use it in GitHub Desktop.
Using gganimate to visualise the chainging computational complexity as n increases.
library(gganimate)
library(ggplot2)
library(dplyr)
library(reshape2)
# Get base n values
n <- 50
base <- data.frame(idx = seq(2, n, by = 0.01))
# Compute relative runtimes
runtimes <- base %>%
mutate(n = idx,
logn = log(idx),
nlogn = idx*log(idx),
n2 = idx**2,
n3 = idx**3,
constant = 1,
root_n = sqrt(idx),
factorial = factorial(idx)) %>%
melt(id.vars = 'idx', variable.name = 'complexity') # %>%
p <- runtimes %>%
ggplot(aes(x = idx, y = value, colour = complexity)) +
geom_line(size = 1) +
ylim(0, 100) +
labs(title = 'Big O Complexity', x = 'Number of Inputs', y = 'Runtime') +
theme_bw() +
transition_reveal(along = idx) +
ease_aes('linear')
p_anim <- animate(p, fps = 20, nframes = 80)
anim_save('big_o.gif')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment