Last active
August 9, 2022 16:24
-
-
Save andrewheiss/2fc5ff0a48f6066825c92fadc680e740 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| library(tidyverse) | |
| library(sf) | |
| library(tigris) | |
| library(ggiraph) | |
| library(glue) | |
| # Get map data from the Census | |
| state_shapes <- states(cb = TRUE) %>% | |
| # Make this column a number | |
| mutate(GEOID = as.numeric(GEOID)) %>% | |
| # Only keep state IDs less than 60 to get rid of Guam, etc | |
| filter(GEOID < 60) %>% | |
| # Get rid of DC | |
| filter(STUSPS != "DC") %>% | |
| # Move HI, AK, and PR | |
| shift_geometry() | |
| # Build a dataset of states and their ACPs | |
| # R has a built-in variable named "state.name" | |
| base_url <- "https://sites.google.com/view/acpinfo/states/" | |
| state_acps <- tibble(NAME = state.name) %>% | |
| mutate(no_acp = NAME %in% c("Alaska", "Arkansas", "Alabama", "Georgia", "South Carolina", "Wyoming", "North Dakota", "South Dakota")) %>% | |
| mutate(state_lower_case = str_to_lower(NAME), | |
| state_dashed = str_replace_all(state_lower_case, " ", "-")) %>% | |
| # Create the label | |
| mutate(url = paste0(base_url, state_dashed)) %>% | |
| mutate(acp_status = ifelse(no_acp, "does not have an ACP", "has an ACP")) %>% | |
| mutate(fancy_label = glue('{NAME} {acp_status}')) %>% | |
| mutate(javascript_link = glue('window.open("{url}")')) | |
| # Join the ACPs data to the GIS data | |
| states_with_acps <- state_shapes %>% | |
| left_join(state_acps, by = "NAME") | |
| # Make a static ggplot plot | |
| fancy_map <- ggplot(states_with_acps) + | |
| geom_sf_interactive(aes( | |
| fill = no_acp, | |
| tooltip = fancy_label, | |
| data_id = NAME, | |
| onclick = javascript_link | |
| ), color = "grey30", size = 0.1) + | |
| scale_fill_manual(values = c("#c5bad4", "#9a83ad")) + | |
| guides(fill = "none") + | |
| theme_void() | |
| # Show the static plot | |
| fancy_map | |
| # Make the static plot interactive! It's clickable too! | |
| x <- girafe(ggobj = fancy_map, width_svg = 4, height_svg = 2) | |
| x <- girafe_options(x, | |
| # Remove the download button thing | |
| opts_toolbar(saveaspng = FALSE), | |
| # Make the cursor act like it's over a link | |
| opts_hover(css = girafe_css(css = "cursor: pointer;"))) | |
| x | |
| # Save the interactive plot as a standalone HTML file | |
| htmltools::save_html(x, "neat_map.html") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment