Skip to content

Instantly share code, notes, and snippets.

@Ax3man
Last active January 31, 2020 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Ax3man/cb472f41f14750a767c9fbef8b862728 to your computer and use it in GitHub Desktop.
Save Ax3man/cb472f41f14750a767c9fbef8b862728 to your computer and use it in GitHub Desktop.
logistic_map.R
# See gif at https://twitter.com/_Axeman_/status/1223037685704474624
library(tidyverse)
library(gganimate)
logistic_map <- function(r, steps = 500, init = .5) {
x <- vector('numeric', steps)
x[1] <- init
for (n in 2:steps) x[n] <- r * x[n-1] * (1 - x[n-1])
return(unique(round(tail(x, -100), 4)))
}
outcomes <- tibble(
r = seq(0.01, 4, by = 0.001),
population = map(r, logistic_map)
) %>%
unnest(population)
p <- ggplot(outcomes, aes(r, population)) +
geom_point(shape = 16, col = 'lightblue', alpha = 0.1, size = 1e-5) +
annotate(geom = 'text', label = "x[n+1] == rx[n](1 - x[n])", x = .7, y = .4, parse = TRUE) +
transition_time(r ^ 3) +
shadow_mark() +
view_zoom_manual(
xmin = c(0, 3), xmax = c(3, 4), ymin = c(0, 0.3), ymax = c(0.75, 1),
wrap = FALSE, ease = 'quadratic-in-out'
) +
labs(x = expression('growth rate' ~ italic(r)), y = expression('population size' ~ italic(x))) +
ggdark::dark_theme_linedraw()
anim_save('logistic_map.gif', p, fps = 20, duration = 10, end_pause = 20, width = 1000, height = 800, res = 300)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment