Skip to content

Instantly share code, notes, and snippets.

@ryantimpe
Last active August 19, 2020 18:38
Show Gist options
  • Save ryantimpe/d4f566fd24ca84f2ea3f7d33bfa37f69 to your computer and use it in GitHub Desktop.
Save ryantimpe/d4f566fd24ca84f2ea3f7d33bfa37f69 to your computer and use it in GitHub Desktop.
Reproduce color prime factorization chart
#Reproduce this prime factorization poster in R
#https://twitter.com/stevenstrogatz/status/1295915404574040065?s=20
library(tidyverse)
#Prime factorization function from SO
# https://stackoverflow.com/questions/49974601/r-prime-factorization
get_prime_factors = function(x){
n=c()
i=2
r=x
while(prod(n)!=x){
if(!r%%i) {n=c(n,i);r=r/i;i=1}
i=i+1
}
n
}
get_prime_factors(9)
#Generate a color palette
#Control the first few primes...
# Make this similar to the original postcad
this_palette_start = tibble::tribble(
~r, ~g, ~b,
255, 255, 255, #white = 1
0, 102, 255, #blue = 2,
255, 0, 51, #maroon = 3,
255, 255, 0, #yellow = 5,
102, 51, 153, #purple = 7,
255, 51, 255, #pink = 11,
204, 153, 102, #brown = 13,
255, 102, 0 #orange = 17
)
#..., then add randoms for the rest
random_channels <- function(n, k=6){
sample(seq(0, 255, length.out = k), n, replace = TRUE)
}
set.seed(43)
nn=30
this_palette_start %>%
bind_rows(
tibble(r = random_channels(nn),
g = random_channels(nn),
b = random_channels(nn))
) %>%
distinct() %>%
mutate(col = rgb(r, g, b, maxColorValue = 255)) %>%
pull(col) -> this_palette
this_palette %>% scales::show_col()
#Generate and plot all factors
tibble::tibble(number = 1:100) %>%
mutate(factors = purrr::map(number, get_prime_factors),
num_factors = purrr::map_dbl(factors, length)) %>%
unnest(factors) %>%
add_row(number=1, factors=1, num_factors=1, .before = 1) -> prime_decomp
prime_decomp %>%
group_by(number) %>%
mutate(x_min = (row_number() - 1)/num_factors,
x_max = (row_number() - 0)/num_factors,
y_min = 0, y_max = 1) %>%
ungroup() %>%
mutate(number_f = factor(number,
levels = as.character(rep(1:10, 10)+rep(9:0, each = 10)*10))) %>%
ggplot()+
geom_rect(aes(xmin=x_min, xmax=x_max, ymin=y_min, ymax=y_max,
fill = as.factor(factors)), color = "black") +
scale_fill_manual(values = this_palette) +
coord_fixed(expand=F, xlim=c(0,1), ylim=c(0,1))+
facet_wrap(~number_f, nrow=10,
strip.position = "bottom") +
theme_void()+
theme(
legend.position = "none",
panel.border = element_rect(fill = NA, size =1.5),
panel.spacing = grid::unit(0, "cm"),
strip.background = element_rect(color = "black")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment