我想同时为多个粒子的位置设置动画。
假设我们有:
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。
发布于 2019-06-13 08:17:51
如果要使所有粒子保持可见,则必须在每个时间点为每个粒子创建行(可以在粒子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)结果:

发布于 2019-06-15 05:00:00
感谢你们的帮助
我得到了这个解决方案:
p<- ggplot(df, aes(x, y))
for (i in 1:3) p<- p + geom_label(data = subset(df,particle ==paste(i)), aes(x = x, y = y,label = particle), size =1, color = i)
p<-p+labs(title = "{frame_time}") +
transition_components(time)
animate(p, fps = 10)https://stackoverflow.com/questions/56571789
复制相似问题