将每种条形颜色堆叠在一起的条形图

时间:2019-04-30 14:17:30

标签: r ggplot2 gganimate

我见过the same question but without a working solutionthis one最初看起来一样,但并没有真正涵盖我的问题。

我想先绘制底部的紫色条并为其设置动画,然后在顶部绘制浅蓝色的条以完成堆叠结果,然后循环。如何使用gganimate软件包。

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

enter image description here

这是我的数据:

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)

1 个答案:

答案 0 :(得分:1)

这是一种预先使用某种操作来指定外观顺序以及每个条出现时的外观的方法。通过预先计算堆叠位置并使用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)

enter image description here