0

I've built an animated barplot with ggplot and gganimate. Nevertheless, I would like to add a title and description every time the graph moves, for example entering the year per each frame.

the actual code is the following:

library(ggplot2)
library(gganimate)
library(animation)
library(gifski)

a <- data.frame(group=df_AllYears$Teams, values=df_16$Average16, 
       frame=rep('a',10))
b <- data.frame(group=df_AllYears$Teams, values=df_17$Average17, 
       frame=rep('b',10))
c <- data.frame(group=df_AllYears$Teams, values=df_18$Average18, 
       frame=rep('c',10))
d <- data.frame(group=df_AllYears$Teams, values=df_19$Average19, 
       frame=rep('d',10))
e <- data.frame(group=df_AllYears$Teams, values=df_20$Average20, 
       frame=rep('e',10))
f <- data.frame(group=df_AllYears$Teams, values=df_21$Average21, 
       frame=rep('f',10))
g <- data.frame(group=df_AllYears$Teams, values=df_22$Average22, 
       frame=rep('g',10))

data <- rbind(a,b,c,d,e,f,g)

ggplot(a, aes(x=group, y=values, fill=group)) + 
  geom_bar(stat='identity')
 
myPlot<- ggplot(data, aes(x=group, y=values, fill=group)) + 
  geom_bar(stat='identity',) +
  scale_fill_manual("legend", values = c("Ferrari"="#BC2129", 
     "McLaren"="#FF8900", "Mercedes"="#029B95", 
     "Toro Rosso"="#0D1623", "Renault"="#FFD503",
     "Red Bull"="#10233B", "Haas F1 Team"="#EA1A39", 
     "Sauber"="#9E2233", 
     "Force India"="#F8AFD2","Williams"="#00A1E4")) +
  theme_bw() +
  theme(axis.text.x = element_blank(), legend.position = "bottom", 
    axis.ticks.x = element_blank(),axis.ticks.y = element_blank(), 
    legend.title = element_blank(), axis.text.y = 
     element_text(hjust = 0), axis.title.y = 
     element_text(vjust = 3), 
     legend.text = element_text(family = "Montserrat Alternates"))
     +
  labs(x="", y="Trend over the years")+
  # gganimate specific bits:
  transition_states(
    frame,
    transition_length = 3,
    state_length = 2
  ) +
  ease_aes('sine-in-out')

# Save at gif:
animate(myPlot, duration = 1, fps = 20, width =400, height =300, 
    renderer = gifski_renderer())
anim_save("outpumarameot.gif")

Really hope someone can help me, I've already spent so many hours on this problem since yesterday.

kjetil b halvorsen
  • 1,206
  • 2
  • 18
  • 28
  • There are examples online and on this forum that show how to do that, e.g. https://stackoverflow.com/questions/53162821/animated-sorted-bar-chart-with-bars-overtaking-each-other/53163549#53163549. If you are running into problems with your specific situation, it will be easier for others to help you if you can make your question reproducible by including some example data as code. – Jon Spring Dec 12 '22 at 14:07

0 Answers0