1

I would like to create an animated bar plot in R which displays the scored goals by each player and gameday.

Below I created fictional data:

df <- data.frame(player = c("Aguero", "Salah", "Aubameyang", "Kane", "Aguero", "Salah", "Aubameyang", "Kane", "Aguero", "Salah", "Aubameyang", "Kane"), 
             team = c("ManCity", "Liverpool", "Arsenal", "Tottenham", "ManCity", "Liverpool", "Arsenal", "Tottenham", "ManCity", "Liverpool", "Arsenal", "Tottenham"), 
             gameday = c(1,1,1,1,2,2,2,2,3,3,3,3),
             goals = c(0,1,2,0,1,1,3,1,2,1,3,2),
             stringsAsFactors = F)

Based on the data I would like to create the animated bar plot. The bar plot should be animated by each game day and display the best scorer above in the plot.

Below I created a created a simple visualization of my idea.

ggplot(data=df, aes(x=reorder(Player, Goals), y=Goals, fill=Team)) +
  geom_bar(stat="identity") +
  theme(legend.position = "none", axis.text.y=element_blank(), 
  axis.title.y=element_blank()) +
  geom_text(aes(label=Player), vjust=1, hjust=-0.1, color="white", size=3.5) +
  coord_flip()

Broad idea of the bar plot

The bar plot is inspired by such a video: https://www.youtube.com/watch?v=U8CpdQnWH7Y

Is there a possibility to create an animated bar plot for that?

Thank you very much for your help!

Albin
  • 822
  • 1
  • 7
  • 25

1 Answers1

2

Yes, to animate ggplots you have the gganimate package. You can find it by looking for [r][ggplot2] animate questions, but as the top answers weren't with the most up to date grammar here is some code:

library("ggplot2")
library("gganimate")
ggplot(data=df, aes(x=reorder(Player, Goals), y=Goals, fill=Team)) +
  geom_bar(stat="identity") +
  theme(legend.position = "none", axis.text.y=element_blank(), 
  axis.title.y=element_blank()) +
  geom_text(aes(label=Player), vjust=1, hjust=-0.1, color="white", size=3.5) +
  coord_flip() +
  ## gganimate code
  labs(title = 'Gameday: {frame_time}') +
  transition_time(gameday) +
  ease_aes('linear')

(Code not tested but should work)

llrs
  • 3,308
  • 35
  • 68
  • Thank you very much for that answer. I also checked the solutions provided in that post: https://stackoverflow.com/questions/53162821/animated-sorted-bar-chart-with-bars-overtaking-each-other – Albin Feb 28 '19 at 12:04
  • Glad to see you found your solution! – llrs Feb 28 '19 at 12:12