1

Update: Sorry I forgot to add the vector:

time=1:100 
value = 1:67
fill = rep(max(value), 100-max(value))

I want to make an animated stacked bar, Here is my example:

library(tidyverse)
library(gganimate)

#example data frame
df <- tibble(time = time, 
             value = c(value, fill),
             x = "A") %>% 
  mutate(fill_color = "gold") %>% 
  mutate(gold_nr = value) %>% 
  mutate(blue_nr = rev(gold_nr)) %>%
  pivot_longer(c(gold_nr, blue_nr),
               names_to = "color_group",
               values_to = "value_group")  


# the code:
p <- df %>% 
  ggplot(aes("", value_group, fill=color_group)) +
  geom_col(width = 0.3, position = position_fill())+
  scale_fill_manual(values = c("gold", "steelblue"))+
  theme_minimal()+
 # theme(legend.position="none")+
  transition_manual(value)+ 
  coord_flip()

animate(p, fps=24, renderer = gifski_renderer(loop = FALSE))

enter image description here

My question is: Why does the bar not stop at 67 and jumps over 75? I think I have to organize the data in a other way?

TarJae
  • 72,363
  • 6
  • 19
  • 66

1 Answers1

1

You should use time column to group the frames.

tail(df, 4)
#     time fill_color color_group value_group
# 197   99       gold     gold_nr          67
# 198   99       gold     blue_nr           2
# 199  100       gold     gold_nr          67
# 200  100       gold     blue_nr           1

The plot now shows correctly the proportions in the last time frame.

proportions(df[df$time == 100, ]$value_group)
# [1] 0.98529412 0.01470588

library('magrittr')

p <- df %>% 
  ggplot2::ggplot(ggplot2::aes("", value_group, fill=color_group)) +
  ggplot2::geom_col(width=0.3, position=position_fill()) +
  ggplot2::scale_fill_manual(values=c("steelblue", "gold")) +
  ggplot2::theme_minimal() +
  ggplot2::coord_flip() +
  gganimate::transition_manual(time)

a <- gganimate::animate(p, fps=24, renderer=gifski_renderer(loop=TRUE))
gganimate::anim_save('a.gif', a)

enter image description here

Note, that your colors were flipped.

jay.sf
  • 60,139
  • 8
  • 53
  • 110
  • This is perfect. Only one question. Why does it not stop at 0.67 and instead at 98. is it possible just to use the values and not proportion? – TarJae Jan 21 '23 at 12:00
  • 1
    @TarJae No clue actually with `ggplot`. But if you're just playing around you could try `mutate(blue_nr=100 - gold_nr)` instead of `rev` when creating `df`. – jay.sf Jan 21 '23 at 12:14
  • 1
    Perfect. This did it! Bravo! – TarJae Jan 21 '23 at 12:17