Skip to content

Instantly share code, notes, and snippets.

@ramongallego
Last active May 1, 2019 21:09
Show Gist options
  • Save ramongallego/3b15d942e840ccae17dac699fe4cb2cc to your computer and use it in GitHub Desktop.
Save ramongallego/3b15d942e840ccae17dac699fe4cb2cc to your computer and use it in GitHub Desktop.
library(tidyverse)
library(gganimate)
library(ggmap)
library(viridis)
library(lubridate)
# We need three things: The data to plot, the map and the location of the samples
# For me, the data looked like a long table with five columns: Site, Date, Species, prevalence and abundance
data.to.plot <- tibble (Site = rep(c("LK", "FH", "CP", "SA", "TR"), each = 10),
Date = ymd(rep(c("20171001", "20171101","20171201","20180101","20180201", "20180301","20180401","20180501","20180601","20180701"), 5)),
Species = rep("Species A", 50),
prevalence = abs(rnorm(50, mean = 0.5, sd = 0.25)),
abundance = abs(rnorm(50, mean = 2000, sd = 5000)))
# The location of the samples
loc <- tibble (Site = c("LK", "FH", "CP", "SA", "TR"),
lat = c(48.51450, 48.54509, 48.44983, 47.85677, 47.60896),
lon = c(-123.1510, -123.0120, -122.9632, -122.6077, -122.9847))
# Getting the map - you need to get a Google maps API key, and paste it on the get_map call
map.for.samples <- get_map(location = c(-125,47,-122,49),
maptype = "terrain",
source = "google",
api_key = "YOUR_KEY_HERE")
# Prepare data for plotting
data.to.plot %>%
left_join(loc) %>%
rownames_to_column(var = "grouping") -> to.plot # Mock variable to make each observation its own point, and the bubles won't move around the map
# the base plot
ggmap(map.for.samples) +
geom_point(data = to.plot, aes(x = lon, y = lat, size = prevalence , color = abundance, group = grouping)) +
scale_size(range = c(2,10)) +
scale_color_viridis()-> p
# The animation #####
p +
facet_wrap(~Species) + # In theory won't need this as there is only one species
labs(title = 'Date: {closest_state}') +
transition_states(fct_reorder(paste(month(Date,label = T), year(Date), sep = "'"),Date), # I wanted the label to look prettier
transition_length = 2,
state_length = 1) +
enter_fade()+
exit_shrink() -> anim
# Saving the animation
anim_save(filename = "animated.map.gif",
animation = anim)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment