Home > Blockchain >  Creating an animated reducing bar chart with gganimate
Creating an animated reducing bar chart with gganimate

Time:01-02

Happy new year to all!

So, 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 to create an animated plot that adds the variable followup (1-720 hrs) that runs backwards and shows how the count is affected.

Ofcourse, 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 have tried using transition_reveal() in the following way (to no avail):

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

Any form of help is appreciated. Thank you!

CodePudding user response:

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

  • Related