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))
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?
CodePudding user response:
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)
Note, that your colors were flipped.