Skip to content

Instantly share code, notes, and snippets.

@yutannihilation
Created February 25, 2024 04:22
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 yutannihilation/36aa39f1cba6c3989b6f46d9fab358d5 to your computer and use it in GitHub Desktop.
Save yutannihilation/36aa39f1cba6c3989b6f46d9fab358d5 to your computer and use it in GitHub Desktop.
library(ggplot2)
library(grid)
size <- unit(70, "points")
x_orig <- unit(0.5, "npc")
y_orig <- unit(0.5, "npc")
gp1 <- gpar(col = "white", fill = "#CEF09D", lwd = 3.3)
gp2 <- gpar(col = "white", fill = "#1C646D", lwd = 3.3)
generate_pattern <- function(angle) {
angle <- angle %% 180
# flip when angle is larger than 45
if (angle <= 45) {
d <- size / cos(pi * angle / 180) # distance between two rectangles
size1 <- size # size of main rectangles
size2 <- size * tan(pi * angle / 180) # size of complement rectangles
} else {
d <- size / cos(pi * (90 - angle) / 180)
size1 <- size / tan(pi * angle / 180)
size2 <- size
}
d1 <- d # distance between main rectangles
d2 <- d / 2 # distance between complement rectangles
# draw main rectangles
l1 <- purrr::pmap(
expand.grid(x = -1:1, y = -1:1),
\(x, y) {
vp <- viewport(
x = x_orig + d1 * x,
y = y_orig + d1 * y,
width = size1,
height = size1,
angle = angle
)
rectGrob(gp = gp1, vp = vp)
}
)
# draw complement rectangles
l2 <- purrr::pmap(
expand.grid(x = c(-1L, 1L), y = c(-1L, 1L)),
\(x, y) {
vp <- viewport(
x = x_orig + d2 * x,
y = y_orig + d2 * y,
width = size2,
height = size2,
angle = angle
)
rectGrob(gp = gp2, vp = vp)
}
)
do.call(grobTree, append(l1, l2))
}
ptn <- generate_pattern(10)
grid.newpage()
grid.draw(ptn)
grid.rect(width = size, height = size, gp = gpar(col = "red", fill = "transparent", alpha = 0.8, lwd = 3))
d <- tempfile()
dir.create(d)
ragg::agg_png(file.path(d, "plot%03d.png"), width = 720, height = 720)
for (i in 0:180) {
patterns <- lapply(1:4 * (0.25 * i), \(angle) pattern(generate_pattern(angle), width = size, height = size, extend = "repeat"))
p <- ggplot(mpg, aes(factor(cyl), fill = factor(cyl))) +
geom_bar() +
scale_fill_manual(values = patterns) +
theme_minimal()
plot(p)
}
dev.off()
gifski::gifski(list.files(d, full.names = TRUE), delay = 0.01)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment