rggplot2missing-datagganimate

gganimate with a missing year


I am trying to animate locations over time using gganimate, and have a dataset running from 2004-2022. Unfortunately I have no data from 2020 (due to COVID). When I try to use gganimate, 2020 shows up in the animation with a bunch of datapoints despite 2020 not being anywhere in my df. How do I plot 2004-2022 without including 2020?

I've tried messing around with nframes and exit_disappear(early=TRUE) to no avail.

Code is below:

with_data <- basemap +
  geom_point(data = metadata, aes(x = `LonDD.v2`, y = `LatDD`, color = `repunit`))+
  facet_wrap(~repunit)+
  scale_color_manual(values = pal_species)

map_with_animation <- with_data +
  transition_time(Year) +
  ggtitle('Year: {frame_time}')
num_years <- max(metadata$Year) - min(metadata$Year) +1
animate(map_with_animation, nframes = num_years, fps = 1)

Solution

  • If one frame per year suits it would be simple to make Year a factor and pass to transition_manual and it would treat level 2021 as coming straight after level 2019:

    library(ggplot2)
    library(gganimate)
    
    df <- tibble::tibble(
      year = rep(c(2015:2019, 2021, 2022), each = 12),
      x = rep(1:12, times = 7),
      y = runif(84, 1, 10)
    )
    
    df |> 
      ggplot(aes(x, y)) +
      geom_line() +
      transition_manual(factor(year)) +
      ggtitle('Year: {current_frame}')
    #> nframes and fps adjusted to match transition
    

    You can do a smooth transition with transition_states and the same factor transformation:

    df |> 
      ggplot(aes(x, y)) +
      geom_line() +
      transition_states(factor(year)) +
      ggtitle('Year: {closest_state}')