gganimate 每种条形颜色的堆叠条形图

gganimate a stacked bar chart per bar color

我看到 the same question but without a working solution. And 一开始看起来一样,但并没有真正涵盖我的问题。

我想先绘制底部的紫色条并设置动画,然后是顶部的浅蓝色条以获得最终的堆叠结果,然后循环。 gganimate 包如何做到这一点。

首先是我的动画条形图,同时显示每年的堆栈。

这是我的数据:

example_df <- structure(list(jaar = c(2019, 2019, 2018, 2018, 2017, 2017, 2016, 
2016, 2015, 2015, 2014, 2014, 2013, 2013, 2012, 2012, 2011, 2011, 
2010, 2010), type = c("purple", "blue", "purple", "blue", "purple", 
"blue", "purple", "blue", "purple", "blue", "purple", "blue", 
"purple", "blue", "purple", "blue", "purple", "blue", "purple", 
"blue"), aantal = c(322L, 338L, 328L, 354L, 303L, 302L, 257L, 
245L, 223L, 185L, 183L, 128L, 141L, 80L, 121L, 58L, 104L, 46L, 
94L, 38L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-20L))

这是我的代码:

library(tidyverse)
library(gganimate)

anim_bar <- example_df %>%
  ggplot(aes(jaar, aantal)) +
  geom_col(aes(fill = type)) +
  scale_fill_manual(values = c("#1beaae", "#6b38e8")) +
  theme(legend.position = "top") +
  transition_time(jaar) +
  shadow_mark() +
  enter_grow() +
  enter_fade()

animate(anim_bar, fps = 20)

这是一种预先使用一些操作来指定出现顺序以及每个条出现时应该是什么样子的方法。通过预先计算堆叠位置并使用 geom_tile.

指定坐标,我运气更好
example_df %>%
  arrange(desc(type), jaar) %>%
  mutate(frame_num = row_number()) %>%
  group_by(jaar) %>%
  mutate(space_below = cumsum(lag(aantal, default = 0))) %>%
  ungroup() %>%

  ggplot() +
  geom_tile(aes(jaar, space_below + aantal/2, 
                width = 0.9, height = aantal,
                fill = type)) +
  scale_fill_manual(values = c("#1beaae", "#6b38e8")) +
  theme(legend.position = "top") +
  transition_time(frame_num) +
  shadow_mark() +
  enter_grow() +
  enter_fade() ->   anim_bar

animate(anim_bar, fps = 20)