GregRousell
GregRousell

Reputation: 1087

How do I make annotations appear at a specific frame using gganimate?

I have a time series line chart that has annotations at specific dates that I'd like to appear only when the animation hits that specific date, and stays until the end of the animation. Below is an example - I'd like the line and text that says "End of WWII" appear once the line hits 1945:

enter image description here

library(tidyverse)
library(gganimate)
library(babynames)

# Keep only 1 name
don <- babynames %>% 
  dplyr::filter(name %in% c("Adolph")) 

# Plot
don %>%
  ggplot(aes(x = year, y = n, group=name)) +
  geom_line(aes (color = name)) +
  ggtitle("Popularity of American names Over Time") +
  ylab("Number of babies born") + 
  annotate ("text", x = 1945, y = 225, label = "End of WWII") +
  geom_segment(aes(x = 1945, y = 0,
                   xend = 1945, yend = 215),
               size = 0.25
  ) + 
  transition_reveal(year)

Upvotes: 1

Views: 581

Answers (1)

Jon Spring
Jon Spring

Reputation: 66765

My approach was to add the text and segment as a layer which appears only at year 1945. I haven't had success so far getting this approach to work with transition_reveal, but it works fine with transition_manual:

annotate_table <- tibble(
  year = 1945,
  label = "End of WWII",
  text_height = 225,
  seg_top = 215
)
don %>%
  dplyr::filter(sex == "M") %>%  # presumably don't need to include the near-zero female Adolphs
  left_join(annotate_table) %>%
  ggplot(aes(x = year, y = n, group=name)) +
  geom_line(aes (color = name)) +
  ggtitle("Popularity of American names Over Time") +
  ylab("Number of babies born") + 
  geom_text(aes(label = label, y = text_height)) +
  geom_segment(aes(xend = year,  yend = seg_top), y = 0, size = 0.25) +
  transition_manual(year, cumulative = TRUE)

enter image description here

Upvotes: 4

Related Questions