The mapgl package aims to expose the powerful map design capabilities of Mapbox GL JS and Maplibre GL JS, while still feeling intuitive to R users. This means that map-making may require a little more code than other mapping packages - but it also gives you maximum flexibility in how you design your maps.
library(tidycensus)
library(mapgl)
fl_age <- get_acs(
geography = "tract",
variables = "B01002_001",
state = "FL",
year = 2022,
geometry = TRUE
)
## Getting data from the 2018-2022 5-year ACS
## Using FIPS code '12' for state 'FL'
fl_map <- mapboxgl(mapbox_style("light"))
fl_map
fl_map |>
add_fill_layer(
id = "fl_tracts",
source = fl_age,
fill_color = interpolate(
column = "estimate",
values = c(20, 80),
stops = c("lightblue", "darkblue"),
na_color = "lightgrey"
),
fill_opacity = 0.5
) |>
add_legend(
"Median age in Florida",
values = c(20, 80),
colors = c("lightblue", "darkblue")
)
brewer_pal <- RColorBrewer::brewer.pal(5, "RdYlBu")
fl_map |>
add_fill_layer(
id = "fl_tracts",
source = fl_age,
fill_color = step_expr(
column = "estimate",
base = brewer_pal[1],
stops = brewer_pal[2:5],
values = seq(25, 70, 15),
na_color = "white"
),
fill_opacity = 0.5
) |>
add_legend(
"Median age in Florida",
values = c(
"Under 25",
"25-40",
"40-55",
"55-70",
"Above 70"
),
colors = brewer_pal,
type = "categorical"
)