3

How can I dynamically change a custom plot annotation in gganimate with relation to transition states, similar to Change label of gganimate frame title, but the annotation should be placed within the plot panel. Animated barplot via gganimate: Annotate box with changing text below plot is similar, but the annotation here is simpler, as it directly relates to the transition states.

library(gganimate)
#> Loading required package: ggplot2

df <- data.frame(y = letters[1:6], x = c(1:6))

p <-
  ggplot(df, aes(x, y)) +
  geom_col() 

p_anim <- p + transition_states(y) + shadow_mark()

## the desired outcome is an annotation which changes according to the transition state. 
tjebo
  • 21,977
  • 7
  • 58
  • 94

1 Answers1

3

You can go down the same route as with the title in the linked question, but you will need to make use of an otherwise rarely used annotation, specifically the "tag". You can position the tag relative to your panel in theme.

library(gganimate)
#> Loading required package: ggplot2

df <- data.frame(y = letters[1:6], x = c(1:6))

p <-
  ggplot(df, aes(x, y)) +
  geom_col() +
  labs(tag = "Animate tag = {closest_state}") +
  theme( 
    ## the tag allows positioning relative to the panel 
    plot.tag.position = c(.7, .2),
    ## so that the tag is always at the same position
    plot.tag = element_text(hjust = 0)
  ) 

p_anim <- p + transition_states(y) + shadow_mark()

animate(p_anim)

Created on 2023-03-07 with reprex v2.0.2

tjebo
  • 21,977
  • 7
  • 58
  • 94