R语言 使用gganimate创建动画缩减条形图

k4ymrczo  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(129)

祝大家新年快乐!
这是Bernard数据集的基本图,显示了不同治疗的死亡率状况。

library(tidyverse)
library(pubh)

Bernard %>% select(fate, treat, followup) %>%
  ggplot(aes(x = treat, fill = fate)) + 
  geom_bar(stat = "count")

我想创建一个动画情节,增加了变量的后续行动(1 - 720小时),运行倒退,并显示如何计数的影响。
当然,这只会影响死亡人数(即减少死亡人数),但我感兴趣的是概念,而不是产出
我尝试过以下面的方式使用transition_reveal()(没有效果):

libary(gganimate)
Bernard %>% select(fate, treat, followup) %>%

  ggplot(aes(x = treat, fill = fate)) + 
  geom_bar(stat = "count") +
  transition_reveal(-followup) +
  labs(title = "Follow-up time: {-frame_along}"

任何形式的帮助我们都很感激。谢谢!

rsaldnfx

rsaldnfx1#

我建议使用一些预处理方法,将“流量”数据点(记录的死亡人数)转化为“存量”数据点(存活参与者的当前数量),可能有一种更简洁的方法,但我希望它能清楚地说明正在发生的事情:

library(tidyverse)
Bernard %>%
  count(treat, fate, followup) %>%
  mutate(status = n * if_else(fate == "Alive", 1, -1)) %>%
  group_by(treat) %>%
  arrange(-followup) %>%
  mutate(alive_count = cumsum(status),
         dead_count  = max(n) - alive_count) %>%
  ungroup() %>%
  select(treat, followup, alive_count, dead_count) %>%
  complete(treat, followup) %>%
  fill(ends_with("count")) %>%
  pivot_longer(alive_count:dead_count) %>% 
  ggplot(aes(treat, value, fill = name)) +
  geom_col() +
  transition_manual(-followup)

相关问题