Step 00 - mapping data US map
library(tidyverse)
usmapdata::us_map("states") %>%
ggplot() +
aes(geometry = geom) +
geom_sf() -> p; p
p$coordinates$crs
## NULL
usmapdata::us_map("states")
## Simple feature collection with 51 features and 3 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -2590847 ymin: -2608148 xmax: 2523581 ymax: 731407.9
## Projected CRS: NAD27 / US National Atlas Equal Area
## # A tibble: 51 × 4
## fips abbr full geom
## <chr> <chr> <chr> <MULTIPOLYGON [m]>
## 1 02 AK Alaska (((-2396847 -2547721, -2393297 -2546391, -2…
## 2 01 AL Alabama (((1093777 -1378535, 1093269 -1374223, 1092…
## 3 05 AR Arkansas (((483065.2 -927788.2, 506062 -926263.3, 53…
## 4 04 AZ Arizona (((-1388676 -1254584, -1389181 -1251856, -1…
## 5 06 CA California (((-1719946 -1090033, -1709611 -1090026, -1…
## 6 08 CO Colorado (((-789538.7 -678773.8, -789538.2 -678769.5…
## 7 09 CT Connecticut (((2161733 -83737.52, 2177182 -65221.22, 21…
## 8 11 DC District of Columbia (((1955479 -402055.2, 1960234 -393571.9, 19…
## 9 10 DE Delaware (((2042506 -284367.3, 2043078 -280000.3, 20…
## 10 12 FL Florida (((1855611 -2064809, 1860157 -2054372, 1867…
## # ℹ 41 more rows
Step 0 - a dream
flat_data %>%
ggplot() +
aes(state_name = state) +
geom_state() +
geom_state_label()
prep reference data
usmapdata::us_map("states") %>%
select(state_name = full, state_abbr = abbr, geometry = geom) %>%
StatSf$compute_panel(coord = CoordSf) %>%
StatSfCoordinates$compute_group(coord = CoordSf) ->
usmaprefdata
usmapcrsinfo <- sf::st_crs(usmapdata::us_map("states"))
compute (join flat w/ reference)
compute_panel_us_states <- function(data, scales){
inner_join(data, usmaprefdata)
}
ggplot2 extension magic - define stat
StatStates <- ggproto("StatStates",
Stat,
required_aes = "state_name|state_abbr",
compute_panel = compute_panel_us_states)
Use stat
state.name %>%
data.frame(state = .) %>%
mutate(is_aeiou = state %>%
str_detect("^[AEIOU]")) %>%
ggplot() +
aes(state_name = state) +
geom_sf(stat = StatStates) +
coord_sf(crs = usmapcrsinfo)
## Joining with `by = join_by(state_name)`
geom_sf
## function (mapping = aes(), data = NULL, stat = "sf", position = "identity",
## na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...)
## {
## c(layer_sf(geom = GeomSf, data = data, mapping = mapping,
## stat = stat, position = position, show.legend = show.legend,
## inherit.aes = inherit.aes, params = list2(na.rm = na.rm,
## ...)), coord_sf(default = TRUE))
## }
## <bytecode: 0x7f861a437b20>
## <environment: namespace:ggplot2>