Skip to content

Instantly share code, notes, and snippets.

@gongcastro
Created October 26, 2020 16:09
Show Gist options
  • Save gongcastro/54d4d87363988fdb5c9a94e573017c94 to your computer and use it in GitHub Desktop.
Save gongcastro/54d4d87363988fdb5c9a94e573017c94 to your computer and use it in GitHub Desktop.
Animated waves using ggplot and gganimate
library(tidyverse)
library(gganimate)
x <- seq(-4*pi, 4*pi, by = pi/50)
k <- seq(4*pi, -4*pi, by = -pi/50)
y <- t(sapply(x, function(x) sin(x-k)))
d <- as.data.frame(cbind(as.matrix(x), y))
colnames(d) <- c("x", k)
d <- pivot_longer(d, -x, "k", values_to = "y") %>%
mutate_at(vars(k), as.numeric)
anim <- ggplot(d, aes(x, y, group = k, colour = k)) +
geom_line(size = 1) +
scale_colour_gradientn(colours = rainbow(8)) +
theme_minimal() +
theme(axis.ticks = element_blank(),
text = element_blank(),
panel.background = element_rect(fill = "black"),
plot.background = element_rect(fill = "black"),
legend.position = "none",
panel.grid = element_blank()) +
transition_time(k)
animate(anim, height = 500, width = 1000)
anim_save("waves.gif")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment