This document provides examples of how to create interactive
choropleth maps of Mexican municipios using the mxmaps and
leaflet packages. The examples show how to visualize data
for all municipios, as well as how to create focused maps of specific
areas, such as cities or metropolitan areas, by subsetting the data.
library("mxmaps")
library("sf")
library("leaflet") # for colorNumeric
df_mxmunicipio_2025$value <- df_mxmunicipio_2025$indigenous /
df_mxmunicipio_2025$pop
# Viridis color scheme
magma <- c(
"#000004FF", "#1D1146FF", "#50127CFF", "#822681FF", "#B63779FF",
"#E65163FF", "#FB8761FF", "#FEC387FF", "#FCFDBFFF"
)
pal <- colorNumeric(magma, domain = df_mxmunicipio_2025$value)
mxmunicipio_leaflet(
df = df_mxmunicipio_2025,
pal = pal,
fillColor = ~ pal(value),
fillOpacity = .7,
weight = .8,
popup = ~ sprintf(
"State: %s<br/>Municipio : %s<br/>Percent Indigenous: %s%%",
state_name, municipio_name, round(value * 100, 1)
)
) |>
addLegend(
position = "bottomright",
pal = pal,
values = df_mxmunicipio_2025$value,
title = "Percent<br>Indigenous",
labFormat = labelFormat(
suffix = "%",
transform = function(x) {
100 * x
}
)
) |>
addProviderTiles("Esri.WorldShadedRelief")City maps
You can also subset the data to only show certain municipios
library("dplyr")
library("geojsonio")
library("jsonlite")
library("RColorBrewer")
df <- df_mxmunicipio_2020 |>
as.data.frame() |>
filter(metro_area %in% c("Valle de México", "Toluca", "Puebla-Tlaxcala"))
df$value <- df$indigenous / df$pop
Reds <- c("white", brewer.pal(4, "RdYlBu"))
pal <- colorNumeric(Reds, domain = df$value)
mxmunicipio_leaflet(
df = df,
fillColor = ~ pal(value),
fillOpacity = 0.5,
zoom = df$region,
popup = sprintf(
"State: %s<br/>Municipio : %s<br/>Value: %s%%",
df$state_name,
df$municipio_name,
round(df$value * 100, 1)
)
) |>
addLegend(
position = "bottomright",
pal = pal,
values = df$value
) |>
addProviderTiles("Esri.WorldTerrain")or you can subset the topoJSON directly
# Convert the topoJSON to spatial object
tmpdir <- tempdir()
# Convert sf to GeoJSON string
geojson_str <- geojsonio::geojson_json(mxmunicipio.topoJSON)
# Convert GeoJSON to TopoJSON
topojson_str <- geojsonio::geo2topo(as.character(geojson_str))
# Write to a file
writeLines(topojson_str, file.path(tmpdir, "mun.topojson"))
muns <- topojson_read(file.path(tmpdir, "mun.topojson"))
# municipios that make up Monterrey
monterrey <- muns[
muns$id %in%
df_mxmunicipio_2020$region[
df_mxmunicipio_2020$metro_area == "Monterrey"
],
]
# Convert to SpatialDataFrame
monterrey <- as_Spatial(monterrey)
# made-up data
monterrey@data$rand <- seq_len(nrow(monterrey@data))
# Create a continuous palette function
pal <- colorNumeric(
palette = "Blues",
domain = monterrey@data$rand
)
leaflet(monterrey) |>
addPolygons(
stroke = TRUE,
smoothFactor = 0.2,
fillOpacity = .7,
weight = 1.2,
fillColor = ~ pal(monterrey@data$rand),
color = "#111"
) |>
addProviderTiles("Esri.WorldTerrain")