Skip to contents

This document provides examples of how to create interactive choropleth maps of Mexican states using the mxmaps and leaflet packages. The examples illustrate how to build maps with both continuous and categorical data, and how to customize the map legends.

## Linking to GEOS 3.12.1, GDAL 3.8.4, PROJ 9.4.0; sf_use_s2() is TRUE
library(leaflet) # for colorNumeric
library(scales) # needed for comma

df_mxstate_2025$value <- df_mxstate_2025$afromexican / df_mxstate_2025$pop
pal <- colorNumeric("Blues", domain = df_mxstate_2025$value)
mxstate_leaflet(
  df = df_mxstate_2025,
  fillColor = ~ pal(value), # Map color to the data column
  popup = ~ sprintf(
    "State: %s<br/>Percent Afro-Mexican: %s",
    state_name,
    comma(value)
  )
) |>
  addLegend(
    position = "bottomright",
    pal = pal,
    values = df_mxstate_2025$value,
    title = "Percent<br>Afro-Mexican",
    labFormat = labelFormat(
      suffix = "%",
      transform = function(x) {
        100 * x
      }
    )
  ) |>
  addProviderTiles("Esri.WorldTerrain")

You can also create maps with categorical variables by first converting the variables to integers and using the colors and labels parameters to addLegend to assign the colors to each level in the variable.

library(mxmaps)
library(leaflet) # for colorBin
library(scales) # needed for comma

df_mxstate_2020$value2 <- factor(sample(c("a", "b", "c", "d", "e"), 32, replace = TRUE))
df_mxstate_2020$value <- as.integer(df_mxstate_2020$value2)

pal <- colorBin(rainbow(5), domain = as.integer(factor(df_mxstate_2020$value2)))
mxstate_leaflet(
  df = df_mxstate_2020,
  fillColor = ~ pal(value),
  weight = 3, # Border thickness
  color = "black", # Border color
  popup = ~ sprintf(
    "State: %s<br/>Percent Afro-Mexican: %s",
    state_name, comma(value)
  )
) |>
  addLegend(
    position = "bottomright",
    colors = c(rainbow(5)),
    labels = c("a", "b", "c", "d", "e"),
    title = "categoría"
  ) |>
  addProviderTiles("Esri.WorldImagery")