library(tidyverse)
library(sf)
library(gganimate)
library(gifski)
library(tigris) # for downloading Census shapefiles
options(tigris_use_cache = TRUE)How to Use gganimate in R
Overview
gganimate is an R package that allows you to animate ggplot2 visualizations. It’s useful for showing changes over time. All you need is a ggplot visual (any kind!) and a field to animate.
Step-by-Step Example
1. Load Required Libraries
2. Create Sample Data
set.seed(123)
states <- c("Alabama", "Alaska", "Arizona", "Arkansas", "California") # Short list for example
years <- 2000:2005
rainbow_sightings <- expand.grid(State = states, Year = years) %>%
mutate(Sightings = sample(0:100, n(), replace = TRUE))3. Download US Census Shapefile
shapefile_path <- "C:\\Users\\herzi\\Downloads\\cb_2018_us_state_5m\\cb_2018_us_state_5m.shp"
states_sf <- st_read(shapefile_path)Reading layer `cb_2018_us_state_5m' from data source
`C:\Users\herzi\Downloads\cb_2018_us_state_5m\cb_2018_us_state_5m.shp'
using driver `ESRI Shapefile'
Simple feature collection with 56 features and 9 fields
Geometry type: MULTIPOLYGON
Dimension: XY
Bounding box: xmin: -179.1473 ymin: -14.55255 xmax: 179.7785 ymax: 71.35256
Geodetic CRS: NAD83
# Keep only the 50 states + DC
states_sf <- states_sf %>%
filter(!STATEFP %in% c("60", "66", "69", "72", "78"))
# Match name field to sample data
states_sf$NAME <- trimws(states_sf$NAME)4. Merge Data
map_data <- states_sf %>%
left_join(rainbow_sightings, by = c("NAME" = "State"))5. Create an Animated Map
animated_map <- ggplot() +
geom_sf(data = map_data, aes(fill = Sightings)) +
scale_fill_viridis_c() +
theme_minimal() +
transition_time(Year) +
labs(title = "Rainbow Sightings: {frame_time}", fill = "Sightings")6. Render and Save the Animation
animated_mapSample code for visualization!
#For making visuals with ggplot2, check out https://ggplot2-book.org
#animate(plotname, duration = durationlength, fps = fpsrate, width = width, height = height, renderer = gifski_renderer())