Created
January 20, 2026 10:12
-
-
Save stephenturner/6f317f51a9613a0a9fc49cd9913c07cf to your computer and use it in GitHub Desktop.
animate-primes.R
This file contains hidden or 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(primes) | |
| library(tidyverse) | |
| primes <- generate_primes(max = 5000) | |
| df <- tibble( | |
| i = 1:length(primes), | |
| primes, | |
| radius = sqrt(primes), | |
| x = radius * cos(primes), | |
| y = radius * sin(primes) | |
| ) | |
| circles <- seq(1000, 5000, by = 1000) | |
| circle_data <- map_df(circles, function(r) { | |
| tibble( | |
| radius_val = r, | |
| primes = seq(0, 2 * pi, length.out = 100), | |
| radius = sqrt(r), | |
| x = radius * cos(primes), | |
| y = radius * sin(primes) | |
| ) | |
| }) | |
| labels_data <- tibble( | |
| radius_val = circles, | |
| radius = sqrt(circles), | |
| x = radius, # at primes = 0 | |
| y = 0, | |
| label = as.character(circles) | |
| ) | |
| p <- ggplot() + | |
| geom_path( | |
| data = circle_data, | |
| aes(x = x, y = y, group = radius_val), | |
| color = "gray30", | |
| linewidth = 0.3 | |
| ) + | |
| geom_text( | |
| data = labels_data, | |
| color = "steelblue", | |
| aes(x = x, y = y, label = label), | |
| hjust = -0.2, | |
| vjust = 0.5, | |
| size = 4, | |
| angle = 45 | |
| ) + | |
| geom_point(data = df, aes(x = x, y = y)) + | |
| coord_fixed() + | |
| theme_void() + | |
| transition_states(i, transition_length = 0, state_length = 1) + | |
| shadow_mark(past = TRUE, future = FALSE) | |
| animate( | |
| p, | |
| nframes = 200, | |
| fps = 20, | |
| width = 600, | |
| height = 600, | |
| renderer = gifski_renderer() | |
| ) | |
| anim_save("primes.gif") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment