Skip to content

Instantly share code, notes, and snippets.

@andrewheiss
Created August 9, 2022 03:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewheiss/71c4b203f6e8b8b3e0c8def18a63122a to your computer and use it in GitHub Desktop.
Save andrewheiss/71c4b203f6e8b8b3e0c8def18a63122a to your computer and use it in GitHub Desktop.
library(tidyverse)
library(sf)
library(tigris)
library(plotly)
state_shapes <- states() %>%
# 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) %>%
# Move HI, AK, and PR
shift_geometry()
# Give every state a random number of sheriffs between 300 to 500, just for fun. You have actual real life data.
states_and_sheriffs <- state_shapes %>%
mutate(number_of_sheriffs = sample(300:500, n(), replace = TRUE)) %>%
# Create a fancier label
mutate(neat_label = paste0("There are ", number_of_sheriffs, " sheriffs here"))
map_with_default_labels <- ggplot() +
geom_sf(data = states_and_sheriffs,
aes(fill = number_of_sheriffs)) +
theme_void()
# Regular plot
map_with_default_labels
# Interactive plot
ggplotly(map_with_default_labels)
# Control the label
map_with_fancy_labels <- ggplot() +
geom_sf(data = states_and_sheriffs,
aes(fill = number_of_sheriffs,
text = neat_label)) +
theme_void()
ggplotly(map_with_fancy_labels, tooltip = "text")
# Save the plot as a standalone HTML file
fun_map_thing <- ggplotly(map_with_fancy_labels, tooltip = "text")
htmlwidgets::saveWidget(fun_map_thing, "whatever.html")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment