Skip to content

Instantly share code, notes, and snippets.

@achetverikov
Last active January 21, 2021 10:49
Show Gist options
  • Save achetverikov/2f4658902712d8acc9dc2d34f7bf5910 to your computer and use it in GitHub Desktop.
Save achetverikov/2f4658902712d8acc9dc2d34f7bf5910 to your computer and use it in GitHub Desktop.
Moving dots with gganimate
library(ggplot2)
library(gganimate)
library(ggthemes)
library(data.table)
n = 80 # number of dots
max_r = 300 # aperture radius
dt <- data.table(r = max_r*sqrt(runif(n)), theta =2*pi*runif(n), dot_n = 1:n)
dt[,x:=r*cos(theta)]
dt[,y:=r*sin(theta)]
dt[,frame:=0]
# speed on x and y
dt[,c('dx','dy'):=.(6,6)]
for(cur_frame in c(1:240)){
dt_cpy<-copy(dt[frame==cur_frame-1])
# some math to make dots reappear on the other side
dt_cpy[,a:=dx^2+dy^2]
dt_cpy[,b:=2*(dx*x+dy*y)]
dt_cpy[,c:=(x^2+y^2)-max_r^2]
dt_cpy[,d:=b^2-4*a*c]
dt_cpy[,t:=pmin((-b + sqrt(d)) / (2 * a), (-b - sqrt(d)) / (2 * a))]
dt_cpy[,x:=x+dx]
dt_cpy[,y:=y+dy]
dt_cpy[,frame := cur_frame]
dt_cpy[,new_r:=sqrt(x^2+y^2)]
dt_cpy[new_r>(max_r+15), c('x','y'):=.(x+dx*t, y+dy*t) ]
dt<-rbind(dt,dt_cpy, fill = T)
}
dt[,dot_gr:=dot_n==10]
dt[,frame_rev := 240-frame]
all_dots <- animate(ggplot(dt, aes(x = x, y = y))+geom_point(size = 3)+ theme_void() + transition_manual(frame), fps = 10)
all_dots
highlight_dot <- animate(ggplot(dt, aes(x = x, y = y, color = dot_gr))+geom_point(size = 3)+scale_color_manual(values = c('gray','red'))+theme_void()+ transition_manual(frame)+theme(legend.position = 'none'), fps = 10)
highlight_dot
highlight_dot_rev <- animate(ggplot(dt, aes(x = x, y = y, color = dot_gr))+geom_point(size = 3)+scale_color_manual(values = c('gray','red'))+theme_void()+ transition_manual(frame_rev)+theme(legend.position = 'none'), fps = 10)
highlight_dot_rev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment