Skip to content

Instantly share code, notes, and snippets.

@dill
Created May 21, 2024 14:19
Show Gist options
  • Save dill/236a929e85983d53a654e25b9a70044b to your computer and use it in GitHub Desktop.
Save dill/236a929e85983d53a654e25b9a70044b to your computer and use it in GitHub Desktop.
Which states in the lower 48 have cities named after them?
### which states of the lower 48 have cities named for them?
### David L Miller 2024
# get all the place names and their lat/long
# https://simplemaps.com/data/us-cities
places <- read.csv("uscities.csv")
library(stringr)
library(maps)
library(ggplot2)
library(ggrepel)
# get cities with names as in the state.name data
ll <- lapply(state.name, \(x){
r <- which(str_detect(string=places$city, paste0("^", x)))
places[r, c("city", "state_name", "lat", "lng")]
})
# name the list
names(ll) <- state.name
# remove states which have no cities
ll <- Filter(\(x){nrow(x) > 0}, ll)
# base map
gg_states <- map_data("state")
# loop over the states
for(i in seq_along(ll)){
# this state
lp <- ll[[i]]
# sorry AK, HI I'm on vacation and don't want to faff with inset maps
if(names(ll)[i] %in% c("Alaska", "Hawaii")) next
# highlight this state
gg_this_state <- map_data("state", names(ll)[i])
# make plot and label
gg <- ggplot() +
geom_polygon(aes(x=long, y=lat, group=group), data=gg_states,
fill="#e5f5f9", colour="white", lwd=0.2) +
geom_polygon(aes(x=long, y=lat, group=group), data=gg_this_state,
fill="#99d8c9") +
geom_point(aes(x=lng, y=lat), data=lp) +
geom_text_repel(aes(x=lng, y=lat, label=city), data=lp) +
ggtitle(names(ll)[i]) +
coord_map() +
theme_void()
ggsave(file=paste0("out/", names(ll)[i],".png"), gg, bg="white",
width=6, height=4)
}
@dill
Copy link
Author

dill commented May 21, 2024

out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment