jb12n
jb12n

Reputation: 473

Animated graph using gganimate

I have a sample data that I would like to plot using an animated graph which shows changes overtime.

#here's the data
df <- structure(list(`Year` = c(2012, 2012, 2012, 2013, 2013, 2013, 2014, 2014, 2014), 
                 `continent` = c("Africa", "Asia", "Europe", "Africa", "Asia", "Europe", "Africa", "Asia", "Europe"),
                 `Cash` = c(400000, 410000, 200000, 300000, 500000, 250000, 400000, 600000, 500000)),
            row.names = c(NA, -9L), class = c("tbl_df", "tbl", "data.frame"))



#here's my attempt at plotting it
ggplot(df, aes(Year, Cash, group = continent)) +
  geom_line(aes(colour = continent)) +
  geom_segment(aes(xend = 2012, yend = Cash), linetype = 2, colour = 'grey')+
  geom_point(size = 2, colour = "white") + 
  geom_text(aes(x = 2012.1, label = continent), hjust = 0)+
  transition_reveal(continent, Year) + 
  coord_cartesian(clip = 'off') + 
  theme(plot.margin = margin(5.5, 40, 5.5, 5.5), legend.position = "none")
#I am getting the error below
Error in ggproto(NULL, TransitionReveal, params = list(along_quo = along_quo,  : 
  object 'Year' not found

#when I remove continent from transition_reveal, i get a plot but it doesn't look nice at all.
#I would like to plot something similar to the picture below

enter image description here

Upvotes: 1

Views: 489

Answers (1)

Jon Spring
Jon Spring

Reputation: 66490

Use transition_reveal(Year) +; the group term in your ggplot(aes()) call takes care of keeping the series separate.

enter image description here

library(gganimate)
a <- ggplot(df, aes(Year, Cash, group = continent)) +
  geom_line(aes(colour = continent)) +
  # Edit - I found the dashed lines distracting when they moved with 
  #   the points, because they were drawn from x = the active Year back
  #   to xend = 2012, making a kind of moire pattern.
  # geom_segment(aes(xend = 2012, yend = Cash), linetype = 2, colour = 'gray40')+
  # Direction of segment reversed below, less distracting
  geom_segment(aes(x = 2012, xend = Year, yend = Cash), linetype = 2, colour = 'gray50')+
  geom_point(size = 2, colour = "white") + 
  geom_text(aes(x = 2012.1, label = continent), hjust = 0, vjust = -0.4) +
  scale_y_continuous(labels = scales::comma) +
  scale_x_continuous(breaks = 2012:2014, minor_breaks = NULL, labels = scales::comma_format(big.mark = "")) +
  transition_reveal(Year) + 
  coord_cartesian(clip = 'off') + 
  theme(plot.margin = margin(5.5, 40, 5.5, 5.5), legend.position = "none")

animate(a, fps = 30, duration = 10, width = 500, height = 250)

Upvotes: 2

Related Questions