Skip to contents

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.

Let’s grab some data from tidycensus on median age by Census tract in Florida and initialize an empty map focused on Florida.

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
fl_map <- mapboxgl(mapbox_style("light"),
                   bounds = fl_age) 

fl_map

Continuous styling

Styling in Mapbox GL JS and Maplibre GL JS is typically handled through expressions. Expressions allow for quite a bit of customization for map-makers, but can feel clunky for R users. mapgl includes several functions to help R users translate their code into expressions for use in their data visualizations.

The interpolate() function will create an interpolate expression, which smoothly transitions values between a series of stops. This means that you can natively create just about any color palette you want and map that palette seamlessly to your data.

Below, we specify two values - 20 and 80 - and map the colors “lightblue” and “darkblue” to those values. Mapbox GL JS will smoothly interpolate colors between light blue and dark blue and map them to data values found in the specified column.

The add_legend() function adds a legend to your map. In mapgl’s initial release, add_legend() does not automatically populate with values from the style. This gives users much more flexibility in how their format their legend, though users also need to take care to ensure that the legend appropriately represents their data. Future updates to the package may include functionality for automated legends.

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")
  )