Skip to content

Instantly share code, notes, and snippets.

@andrewheiss
Created August 9, 2022 03:31
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 andrewheiss/b944552346525f8a384bd5ac9ca5bae1 to your computer and use it in GitHub Desktop.
Save andrewheiss/b944552346525f8a384bd5ac9ca5bae1 to your computer and use it in GitHub Desktop.
library(tidyverse)
library(sf)
library(tigris)
library(plotly)
library(glue)
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()
# The census includes a bunch of extra columns in the data, so I'll just paste
# them together in some text using glue(), which replaces the {TEXT} with values
# from the data. This column can be whatever you want, in the end.
# <br> adds a line break
state_shapes_with_info <- state_shapes %>%
mutate(info_label = glue("This is the state of {NAME} and<br> its FIPS code is {GEOID}.<br>Its USPS abbreviation is {STUSPS}"))
# "group" is an invisible aesthetic that doesn't change anything in the plot,
# but lets you map a column to the plot anyway
map_with_info_labels <- ggplot() +
geom_sf(data = state_shapes_with_info,
aes(group = GEOID,
text = info_label),
fill = "dodgerblue", color = "grey90", size = 0.1) +
theme_void()
ggplotly(map_with_info_labels, tooltip = "text")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment