Skip to content

Instantly share code, notes, and snippets.

@fmichonneau
Created October 13, 2020 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmichonneau/2c4a06b2642f617c837de47aa8068ead to your computer and use it in GitHub Desktop.
Save fmichonneau/2c4a06b2642f617c837de47aa8068ead to your computer and use it in GitHub Desktop.
Create animated map of all Carpentries workshops through time
library(jsonlite)
library(tidyverse)
library(maps)
library(gganimate)
library(countrycode)
workshop_data <- jsonlite::fromJSON(
"https://feeds.carpentries.org/all_workshops.json"
)
workshop_data <- workshop_data %>%
filter(start_date < Sys.Date()) %>%
filter(latitude < 90) %>%
mutate(year = lubridate::year(start_date)) %>%
filter(
country != "W3", country != "",
(latitude != -48.876667 & longitude != 123.39333)) %>%
mutate(
country_name = countrycode(
country,
"iso2c",
"country.name"
),
start_date = readr::parse_date(start_date)
)
sum_by_country <- workshop_data %>%
count(year, country_name) %>%
complete(year, country_name, fill = list(n = 0)) %>%
group_by(country_name) %>%
mutate(
cumulative_n = cumsum(n),
cumulative_n = replace(cumulative_n, cumulative_n == 0, NA)
)
world <- map_data("world") %>%
mutate(region_2 = countrycode(
region,
"country.name",
"country.name"
))
workshop_plot_data <- map_df(
unique(sum_by_country$year),
function(.x) {
left_join(
world, filter(sum_by_country, year == .x),
by = c("region_2" = "country_name")
) %>%
mutate(
year = replace_na(year, min(year, na.rm = TRUE)),
start_date = parse_date(paste0(year, "-12-31"))
)
}
)
workshop_plot_data <- bind_rows(
world %>%
mutate(
n = NA,
cumulative_n = NA,
start_date = as.Date("2011-12-31")
),
workshop_plot_data
)
anim <- ggplot() +
geom_map(
data = workshop_plot_data,
aes(fill = cumulative_n, x = long, y = lat, map_id = region),
map = world
) +
scale_fill_viridis_c(
na.value = "gray70",
breaks = c(1, 10, 100, 500),
trans = "log", name = "Number of Workshops"
) +
geom_point(
data = workshop_data,
aes(x = longitude, y = latitude),
color = "#dda631",
inherit.aes = FALSE
) +
coord_quickmap() +
theme_minimal() +
theme(legend.position = "bottom") +
labs(
x = "", y = ""
) +
scale_color_identity(guide = FALSE) +
transition_time(start_date)
## gif version
anim_map <- animate(anim, width = 800, height = 600, res = 144)
anim_save("map-workshop-through-time-animation.gif", anim_map)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment