Skip to content

Instantly share code, notes, and snippets.

@dmi3kno
Created December 6, 2017 14:51
Show Gist options
  • Save dmi3kno/5585e31af79914c2f751d1de70854b78 to your computer and use it in GitHub Desktop.
Save dmi3kno/5585e31af79914c2f751d1de70854b78 to your computer and use it in GitHub Desktop.
Animate ggplot snowflakes
library(tidyverse)
library(tweenr)
library(magick)
m <- 2e2
min_s <- 4
k <- 2e2/(min_s)
img <- image_graph(600, 600, res = 96)
plot_snowflakes <- function(data){
p <- ggplot(data, aes(x,y, size=size))+
geom_point(color="white", pch=42)+
scale_size_identity()+
coord_cartesian(c(0,1), c(0,1))+
theme_void()+
theme(panel.background = element_rect(fill = "black"),
plot.background = element_rect(fill = "black"))
print(p)
}
merge(
tibble(t = seq(k)),
tibble(id = seq(m), d = runif(m),
x = runif(m), y = runif(m)*5,
size = runif(m, min=min_s, max=5*min_s))) %>%
mutate(y = y - t * size / 2e2,
x = jitter(x),
ease = 'linear') %>%
tween_elements(time="t", group = "id",
ease="ease",
nframes = 2e2) %>%
filter(y>=0, t<k) %>%
group_by(.frame) %>%
nest() %>% pull(data) %>%
walk(.f=plot_snowflakes)
dev.off()
animation <- image_animate(img, fps = 25)
#print(animation)
image_write(animation, "snowflake.gif")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment