我正在尝试为我的动画添加一行,但我无法使用框架的概念使其工作。这是一个可重复的例子:
df <- read.table(header = TRUE, text = 'key value bins maxIntensity
A 4 0 1
A 1 1 1
A 0 2 1
B 3 0 2
B 2 1 2
B 5 2 2
D 2 0 1
D 3 1 1
D 0 2 1')
可以使用gganimate包创建动画:
library('animation')
library('gganimate')
par(bg = "white")
g <- ggplot(df, aes(xmin = df$bins, xmax = df$bins + 1, ymin = 0, ymax = df$value, frame = df$key))
g <- g + geom_rect(fill=alpha("Orange", alpha = 1))
g <- g + labs(title = "Test Histogram")
g <- g + scale_y_continuous(labels = scales::comma)
gganimate(g, ani.width=400, ani.height=400, interval = .4, "test.gif")
哪种方法很好。
现在我想在每个帧的不同位置添加一行。该位置在df$maxIntensity
中指定。
所以,我想我应该补充一点:
g <- g + geom_vline(xintercept = df$maxIntensity, lty=3, color = "black")
但是,它只是在每一帧上一次性添加所有行。知道如何在每个帧中添加一行吗?
答案 0 :(得分:3)
制作一个可重复的例子让我有一个更快的代码,我可以尝试很多不同的选项。 (我的原始代码需要大约10分钟才能向我显示任何结果。)
因此,关键是要再次frame
添加geom_vline
:
g <- g + geom_vline(aes(xintercept = df$maxIntensity, frame = df$key))
所以,代码看起来像:
par(bg = "white")
g <- ggplot(df, aes(xmin = df$bins, xmax = df$bins + 1, ymin = 0, ymax = df$value, frame = df$key))
g <- g + geom_rect(fill=alpha("Orange", alpha = 1))
g <- g + geom_vline(aes(xintercept = df$maxIntensity, frame = df$key), lty=2, size = 1, color = "black")
g <- g + labs(title = "Test Histogram")
g <- g + scale_y_continuous(labels = scales::comma)
gganimate(g, ani.width=400, ani.height=400, interval = .4, "test.gif")