r - 如何在 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。
解决方案
如果要保持所有粒子可见,则必须在每个时间点为每个粒子创建行(您可以在粒子 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)
结果:
推荐阅读
- post - 这个 POST 请求有什么问题?
- matlab - 如何在 MATLAB 中创建矩阵输出?
- excel - VBA:设置单元格的值“对象'范围'的方法'值'失败”
- ios - 锁定屏幕上的通知/小部件与 Swift 中的按钮
- angular - 在 Angular 库中安装依赖项
- scala - 如何使用 ScalaMock 评估使用某些 Spark Dataframe 参数调用的函数并具有有用的输出
- flutter - 有没有办法为整个包/lib/文件夹设置`//@dart=2.12`?
- c# - 如何将模型映射到数据库
- python - Python - Sklearn - 具有数千个变量的多元线性回归
- conv-neural-network - 为什么 Grad CAM 需要调整为 224 x 224