如何将geom_smooth(method = "lm) 函数与gganimate() 的transition_layers 结合起来,以便当各个条向上漂移/增长时,geom_smooth 的线性线出现,如下所示:geom_smooth 线所需外观的示例 https://user-images.githubusercontent.com/1775316/49728400-f0ba1b80-fc72-11e8-86c5-71ed84b247db.gif唯一的区别是,在我的例子中,当线条出现时,条形图会向上漂移,而不是点。
目前的条形效果很好,通过向上漂移而出现,这是通过使用 gganimate 的transition_layers 函数实现的。
但是,我不知道如何添加 geom_smooth 线,因此它会随着条形向上生长而出现。现在,该行出现在末尾,如下所示。
请参阅下文了解动画的当前外观。
这是我的问题的简单表示:
#Df for reprex
library(ggplot2)
library(tidyverse)
year <- as.numeric(c(1996:2002,
1996:2002,
1996:2002))
c <- c(39, 40, 67, 80, 30, 140, 90, 23, 100, 123,
140, 1, 2, 1, 13, 3, 3, 30, 1, 3, 3)
df <- data.frame(year, c) %>%
select(year, c) %>%
arrange(year)
#Static plot
(static_plot <- ggplot(data = df) +
geom_bar(data = df %>% filter(year == 1996), stat="identity", position ="stack",
aes(x = year, y = c)) +
geom_bar(data = df %>% filter(year == 1997), stat="identity", position ="stack",
aes(x = year, y = c)) +
geom_bar(data = df %>% filter(year == 1998), stat="identity", position ="stack",
aes(x = year, y = c)) +
geom_bar(data = df %>% filter(year == 1999), stat="identity", position ="stack",
aes(x = year, y = c)) +
geom_bar(data = df %>% filter(year == 2000), stat="identity", position ="stack",
aes(x = year, y = c)) +
geom_bar(data = df %>% filter(year == 2001), stat="identity", position ="stack",
aes(x = year, y = c)) +
geom_bar(data = df %>% filter(year == 2002), stat="identity", position ="stack",
aes(x = year, y = c)) +
labs(y = "year",
x = "c",
title = "Reprex") +
geom_smooth(df, mapping = aes(x = year, y = c), method = "lm",
colour = "black", se = F)
)
#Animation
library(gganimate)
anim <- static_plot +
transition_layers(layer_length = 1, transition_length = 1) +
enter_drift(x_mod = 0, y_mod = -max(df$c))
animate(anim, fps = 10, duration = 10,
width = 600, height = 500, renderer = gifski_renderer())