Search code examples
rggplot2mapsgganimate

Animating maps with changing shapefiles (only 4 different shapefiles) hangs


Im trying to create an animation of the growth of US borders per year. While I am able to generate each individual plot rapidly, the animation hangs when I try to create an animated map (no progress bar) even with low number of frames.

Here is some example code with 4 dates, any ideas on how to generate the animation?

    library(USAboundaries)
    library(dplyr)
    library(ggplot2)
    library(gganimate)
    
    dates <- seq(as.Date("1783-09-03"), as.Date("2000-12-31"), by="years")
    dates <- dates[c(1,29, 52, 75)]
    maps <- lapply(dates, function(date) {
      map <- us_states(map_date = date, resolution = "high")
      map$year <- date
      map
    }) %>%
      bind_rows() %>%
      select(id_num, terr_type, state_code, geometry, year, name)
    # Generating all the maps at once works just fine
    all_maps <- ggplot() +
      geom_sf(data = maps)
    all_maps
    # Animating maps hangs once its called
    animated_map <- ggplot() +
      geom_sf(data = maps) +
      transition_states(
        year,
        transition_length = 2,
        state_length = 1
      )
    animated_map

Solution

  • You can use transition_manual. Try this on your maps

    animated_map <- ggplot() +
      geom_sf(data = maps) +
      transition_manual(year)
    
    animate(animated_map, renderer = gifski_renderer())
    

    Please note that I am using gifski_renderer() from gifski package. If you have full access to the default location, you may not need that. You get the following output:

    output