首页 > 解决方案 > 如何在 R 中为粒子运动设置动画

问题描述

我想同时为许多粒子的位置设置动画

假设我们有:

df <- data.frame(
    x = c(1,2,3,4,5,6,7,8,9,10), 
    y = c(2,3,4,5,6,7,8,9,10,1),
    particle = c(1,1,2,3,1,3,1,3,2,1),
    time = 1:10 )

这意味着:粒子 1 在时间 1 处于位置 (x=1, y=2) 然后在时间 2 到达位置 (x=2, y=3),以此类推。

粒子 2 在时间 3 出现在位置 (x=3, y=4) 并在时间 9 移动到其他位置。

等等

我试过这个:

ggplot(df, aes(x, y), show.legend=FALSE)  +  
    geom_point() +
    transition_states(time)

但动画同时只显示一个粒子。

如何为所有粒子设置动画(在示例中,三个粒子必须始终可见)

谢谢。

BT。

标签: ranimationggplot2

解决方案


如果要保持所有粒子可见,则必须在每个时间点为每个粒子创建行(您可以在粒子 2 和 3 出现之前省略行)。这样做tidyverse

library(tidyverse)

expanded = df %>%
    # Create rows for each combination of particle and time
    complete(particle, time) %>%
    group_by(particle) %>%
    arrange(time) %>%
    # Fill missing x and y with the current position, up to
    #   the next change for that particle
    fill(x, y, .direction = "down")

# Make particle a factor
ggplot(expanded, aes(x, y, colour = factor(particle)))  +  
    geom_point() +
    transition_states(time)

结果:

在此处输入图像描述


推荐阅读