rggplot2bar-chartgganimate

Animated reducing bar chart with gganimate


I have this basic plot of the Bernard dataset, that shows the mortality status by treatment.

library(tidyverse)
library(pubh)

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

enter image description here

I would like an animated plot that adds the variable followup (1-720 hours) that runs backwards and shows how the count is affected.

Of course, this only affects the population of people who died (i.e. reducing their count), still I am interested in the concept, not so much the output.

I tried 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}"

enter image description here


Solution

  • I'd suggest using some preprocessing to turn your "flows" data points (recorded deaths) into a "stock" (current counts of living participants). There's probably a more concise way to go about this but I hope it's clear what's happening:

    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)
    

    enter image description here