【问题标题】:gganimate a stacked bar chart per bar colorgganimate 每个条形颜色的堆叠条形图
【发布时间】:2023-04-09 07:29:01
【问题描述】:

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

我想首先绘制底部紫色条并为其设置动画,然后在顶部绘制浅蓝色条以完成堆叠结果,然后循环。使用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)

【问题讨论】:

  • 请问您为什么要这样做?似乎很难“阅读”图表
  • 我通过澄清我想要的结果问题来编辑我的问题。我想通过动画阐明增长趋势和大量分享浅蓝色的戏剧。

标签: r ggplot2 gganimate


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 2017-04-27
    • 1970-01-01
    • 2021-02-25
    • 2023-03-28
    相关资源
    最近更新 更多