Last active
July 4, 2024 22:19
-
-
Save JEFworks/c59b835ef855f74c17513b074e5c6d92 to your computer and use it in GitHub Desktop.
Using gganimate to create an animation of fireworks over a background image
This file contains 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
## following https://alistaire.rbind.io/blog/fireworks/ | |
## but manually convert to polar coordinates to be able to add | |
## background image, which cannot be used with coord_polar() | |
library(ggplot2) | |
library(gganimate) | |
theme_set(theme_void()) | |
## create set of points in polar coordinates | |
set.seed(0) | |
data <- expand.grid( | |
r = seq(5)-0.9, ## 5 rings starting from r=0.1 to r=4.1 | |
theta = runif(50, 0, 360) * pi / 180 ## 30 randomly distributed particles per ring | |
) | |
## convert from polar coordinates to cartesian for plotting | |
data_polar <- data.frame(x = data$r * cos(data$theta), | |
y = data$r * sin(data$theta)) | |
## add time for animation later | |
data_polar$t <- rep(1:5, 50) ## time for animation | |
## plot with ggplot | |
g <- ggplot(data_polar) + | |
geom_point(aes(x,y,col=t)) | |
g | |
## add a background_image | |
library(ggpubr) | |
library(png) | |
## download and modify from | |
## https://www.freepik.com/free-vector/cityscape-night_2987104.htm | |
url <- "background.png" | |
bg_image <- readPNG(url) | |
gg <- ggplot(data_polar) + | |
background_image(bg_image) + | |
geom_point(aes(x,y,col=t)) + | |
scale_color_gradient(low="white", high="#f8eca4") + | |
guides(color = FALSE) + | |
xlim(-8.5,8.5) + ylim(-12,5) | |
gg | |
## animate | |
p <- gg + | |
transition_time(t) + | |
shadow_wake(1) ## make firework trail longer | |
animate(p, fps = 100, nframes = 30) |
Author
JEFworks
commented
Jul 4, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment