0

I have two ggplot animations from two different datasets, one is animation for geom_path, the other is for geom_points. I want to combine them together with the same time state, and the expected result looks like Make multiple geoms animated in ggplot.

enter image description here enter image description here

Here is my R code

library(ggplot2)
library(gganimate)
xx=c(1,1)
vv=c(-1,0)
ep=0.2
L=5
dl=10
s=15
#generate data
data<-matrix(0,L*dl,2)
data_all<-matrix(0,L*dl*s,2)
for(i in 1:L){
  for(j in 1:(s*dl)){
    data_all[(i-1)*s*dl+j,]=cos(2*ep*(j-1))*xx+sin(2*ep*(j-1))*vv
  }
  for(j in 1:dl){
    data[(i-1)*dl+j,]=cos(ep*(j-1))*xx+sin(ep*(j-1))*vv
    if(j==dl){
      xx=data[i*dl,]
      vv=rnorm(2)*4
    }
  }
}
t<-rep(c(1:L),each=dl)
dat=cbind(t,data)
dat<-as.data.frame(dat)
colnames(dat)=c("t","x1","x2")
p1=ggplot(dat,aes(x = x1, 
                 y = x2)) +
  geom_path()+
  transition_reveal(t)
p1  

t2<-rep(c(1:L),each=dl*s)
dat_all=cbind(t2,data_all)
dat_all<-as.data.frame(dat_all)
colnames(dat_all)=c("t","x1","x2")
pp=ggplot(dat_all,aes(x = x1, y = x2)) +
  geom_point()
p2 <- pp + 
  transition_states(t,
                    transition_length = 0.1,
                    state_length = 5)

p2
Xia.Song
  • 416
  • 3
  • 15

1 Answers1

1

Something like this?

library(ggplot2)
library(gganimate)
xx=c(1,1)
vv=c(-1,0)
ep=0.2
L=5
dl=10
s=15
#generate data
data<-matrix(0,L*dl,2)
data_all<-matrix(0,L*dl*s,2)
for(i in 1:L){
  for(j in 1:(s*dl)){
    data_all[(i-1)*s*dl+j,]=cos(2*ep*j)*xx+sin(2*ep*j)*vv
  }
  for(j in 1:dl){
    data[(i-1)*dl+j,]=cos(ep*j)*xx+sin(ep*j)*vv
    if(j==dl){
      xx=data[i*dl,]
      vv=rnorm(2)*4
    }
  }
}

t<-rep(c(1:L),each=dl)
dat=cbind(t,data)
dat<-as.data.frame(dat)
colnames(dat)=c("t","x1","x2")


t2<-rep(c(1:L),each=dl*s)
dat_all=cbind(t2,data_all)
dat_all<-as.data.frame(dat_all)
colnames(dat_all)=c("t","x1","x2")


ggplot(dat,aes(x = x1, y = x2)) +
  geom_path()+
  geom_point(data=dat_all) +
  transition_reveal(t) 

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66
  • Maybe my description is not exact. What I expect is that in each frame, when the path is moving, there is an ellipse was shown as a background(p2). And I already group the data contains in the same ellipse by t. – Xia.Song Oct 25 '21 at 06:04