Bjö*_*örn 9 animation r ggplot2 gganimate
这是一个静态图的可复制示例,我想对其进行动画处理(我想显示MCMC采样器的行为)。
library(tidyverse)
library(gganimate)
set.seed(1234)
plot_data <- tibble(x=cumsum(rnorm(100)),
y=cumsum(rnorm(100)),
time=1:length(x))
ggplot(data=plot_data,
aes(x=y, y=x)) +
geom_point() + geom_line()
Run Code Online (Sandbox Code Playgroud)
我想看到的是绘制点时它们是可见的,然后一点点褪色(即alpha从例如1变为0.3),而会有一条线仅显示最近的历史(理想情况下是淡色显示最近的历史最少消失,多退后几步完全消失)。
以下内容或多或少地实现了我想要的点(因此,从某种意义上讲,我只想向此点添加渐变线以连接最后几个点-点在某些帧上越慢渐变越好):
ggplot(data=plot_data,
aes(x=y, y=x)) +
geom_point() +
transition_time(time) +
shadow_mark(past = T, future=F, alpha=0.3)
Run Code Online (Sandbox Code Playgroud)
我正在努力的是如何为两个几何(例如点和线)添加两个不同的行为。例如,在下面的点消失了(我不希望它们消失),线条也没有褪色(我希望它们消失)。
p <- ggplot(data=plot_data,
aes(x=y, y=x)) +
geom_point() +
transition_time(time) +
shadow_mark(past = T, future=F, alpha=0.3)
p + geom_line() +
transition_reveal(along = time) +
shadow_mark(past = T, future=F, alpha=0.3)
Run Code Online (Sandbox Code Playgroud)
Jon*_*ing 15
我无法使用内置shadow_*
函数来一次控制多个行为。它似乎只适用于最新的一种。(使用gganimate 1.0.3.9000)
解决此问题的一种方法是手动计算转换。例如,我们可以将数据复制100次,每帧复制一份,然后分别为我们的点层和段层分别指定alpha。
plot_data %>%
uncount(100, .id = "frame") %>%
filter(time <= frame) %>%
arrange(frame, time) %>%
group_by(frame) %>%
mutate(x_lag = lag(x),
y_lag = lag(y),
tail = last(time) - time,
# Make the points solid for 1 frame then alpha 0.3
point_alpha = if_else(tail == 0, 1, 0.3),
# Make the lines fade out over 20 frames
segment_alpha = pmax(0, (20-tail)/20)) %>%
ungroup() %>%
ggplot(aes(x=y, y=x, xend = y_lag, yend = x_lag, group = time)) +
geom_segment(aes(alpha = segment_alpha)) +
geom_point(aes(alpha = point_alpha)) +
scale_alpha(range = c(0,1)) +
guides(alpha = F) +
transition_manual(frame)
Run Code Online (Sandbox Code Playgroud)
(对于此渲染,我将其包裹在中animate( [everything above], width = 600, height = 400, type = "cairo")
)