rggplot2gganimate

Issue with Label Behaviour in gganimate


I am using gganimate to display line charts, animating between two different areas.

I want a label to appear at each point, displaying a formatted version of the number.

During the transitions, the labels are moving through random values, before settling on the right values after the transition is over.

How do I make the labels only appear once the transition is completed, or alternatively how do I get the labels to snap between the two values?

library(dplyr)
library(ggplot2)
library(gganimate)
library(scales)
library(lubridate)


Minimum_Viable <- tibble(
  AreaCode = c("A", "A", "B", "B"),
  Date = c(ymd("2022-11-24"), ymd("2025-05-08"), ymd("2022-11-24"), ymd("2025-05-08")),
  Value = c(56800, 54000, 58000, 62000)
) %>%
  mutate(Label = label_comma()(Value))

Animation_Test <- ggplot(Minimum_Viable,
                         aes(x = Date, y = Value, label = Label)) +
  geom_line(color = "red") +
  geom_point(color = "red") +
  geom_label() +
  labs(title = "{closest_state} Value") +
  transition_states(AreaCode,
                    transition_length = 1,
                    state_length = 2) +
  theme_minimal()


Solution

  • Based off a comment from @Jon Spring, adding spaces with paste0 fixes the issue.

    This is related to a known bug: https://github.com/thomasp85/gganimate/issues/512

    library(dplyr)
    library(ggplot2)
    library(gganimate)
    library(scales)
    library(lubridate)
    
    
    Minimum_Viable <- tibble(
      AreaCode = c("A", "A", "B", "B"),
      Date = c(ymd("2022-11-24"), ymd("2025-05-08"), ymd("2022-11-24"), ymd("2025-05-08")),
      Value = c(56800, 54000, 58000, 62000)
    ) %>%
      mutate(Label = label_comma()(Value))
    
    #contains issue
    Animation_Test <- ggplot(Minimum_Viable,
                             aes(x = Date, y = Value, label = Label)) +
      geom_line(color = "red") +
      geom_point(color = "red") +
      geom_label() +
      labs(title = "{closest_state} Value") +
      transition_states(AreaCode,
                        transition_length = 1,
                        state_length = 2) +
      theme_minimal()
    
    #use paste0 on the label to fix it.
    Minimum_Viable <- Minimum_Viable %>%
    mutate(Label_Workaround = paste0(" ", Label))
    
    #now snaps to nearest value
    Animation_Workaround <- ggplot(Minimum_Viable,
                             aes(x = Date, y = Value, label = Label_Workaround)) +
      geom_line(color = "red") +
      geom_point(color = "red") +
      geom_label() +
      labs(title = "{closest_state} Value") +
      transition_states(AreaCode,
                        transition_length = 1,
                        state_length = 2) +
      theme_minimal()