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 = 2023,
  geometry = TRUE
)
## Getting data from the 2019-2023 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.

For continuous color scales, the interpolate_palette() function automatically calculates appropriate break points and creates smooth color transitions. You can specify the classification method (“equal”, “quantile”, or “jenks”) and either a palette function or specific colors:

# Automatic continuous scale with equal breaks
continuous_scale <- interpolate_palette(
  data = fl_age,
  column = "estimate",
  method = "equal",
  n = 5,
  palette = viridisLite::plasma
)

fl_map |>
  add_fill_layer(
    id = "fl_tracts",
    source = fl_age,
    fill_color = continuous_scale$expression,
    fill_opacity = 0.5
  ) |>
  add_legend(
    "Median age in Florida",
    values = get_legend_labels(continuous_scale, digits = 0),
    colors = get_legend_colors(continuous_scale),
    type = "continuous"
  )