【问题标题】:Combine multiple ggplot animation together?将多个ggplot动画组合在一起?
【发布时间】:2021-12-09 15:09:50
【问题描述】:

我有两个来自两个不同数据集的 ggplot 动画,一个是 geom_path 的动画,另一个是 geom_points 的动画。我想将它们与相同的时间状态结合在一起,预期的结果类似于Make multiple geoms animated in ggplot

这是我的 R 代码

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

【问题讨论】:

    标签: r ggplot2 gganimate


    【解决方案1】:

    这样的?

    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) 
    
    

    【讨论】:

    • 也许我的描述不准确。我期望的是,在每一帧中,当路径移动时,会有一个椭圆显示为背景(p2)。而且我已经将数据包含在同一个椭圆中按 t 分组。
    猜你喜欢
    • 2013-03-20
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    相关资源
    最近更新 更多