1. Introducción

Este cuaderno ilustra la cartografía temática para el departamento del Putumayo en Colombia. Según Amanda Briney, un mapa temático enfatiza un tema o tópico específico, como la distribución de la producción agrícola por municipio. A diferencia de los mapas de referencia general, los mapas temáticos muestran patrones espaciales de variables específicas.

Los tipos de mapas temáticos más usados son:

2. Datos

Se utilizan las siguientes fuentes:

3. Preparación

3.1 Librerías

library(sf)
## Linking to GEOS 3.14.1, GDAL 3.12.1, PROJ 9.7.1; sf_use_s2() is TRUE
library(dplyr)
## 
## Adjuntando el paquete: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(readr)
library(stringr)
library(classInt)
library(ggplot2)
library(ggrepel)
library(tmap)
library(cartography)
## Warning: package 'cartography' was built under R version 4.6.1
## This project is in maintenance mode. 
## Core functionalities of `cartography` can be found in `mapsf`.
## https://riatelab.github.io/mapsf/
library(leaflet)
library(htmltools)

3.2 Directorio de trabajo

setwd("C:\\Users\\ASUS\\OneDrive\\Documents\\unal\\GB2\\proyecto 4")

4. Lectura de datos

4.1 Datos de frutales

frutales <- read_csv(".//put_tropicales_2022.csv", show_col_types = FALSE)
head(frutales)

4.2 Datos espaciales

# Municipios y departamentos de Colombia
colombiaMpios <- st_read(".\\Datos\\SHP_MGN2018_INTGRD_MPIO\\MGN_ANM_MPIOS.shp")
## Reading layer `MGN_ANM_MPIOS' from data source 
##   `C:\Users\ASUS\OneDrive\Documents\unal\GB2\proyecto 4\Datos\SHP_MGN2018_INTGRD_MPIO\MGN_ANM_MPIOS.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 1122 features and 90 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -81.73562 ymin: -4.229406 xmax: -66.84722 ymax: 13.39473
## Geodetic CRS:  MAGNA-SIRGAS
colombiaDepto <- st_read(".//Datos//SHP_MGN2018_INTGRD_DEPTO//MGN_ANM_DPTOS.shp")
## Reading layer `MGN_ANM_DPTOS' from data source 
##   `C:\Users\ASUS\OneDrive\Documents\unal\GB2\proyecto 4\Datos\SHP_MGN2018_INTGRD_DEPTO\MGN_ANM_DPTOS.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 33 features and 88 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -81.73562 ymin: -4.229406 xmax: -66.84722 ymax: 13.39473
## Geodetic CRS:  MAGNA-SIRGAS
# Ciudades del mundo
cities2 <- read.csv(".//Datos//WORLD_CITIES//worldcities.csv", sep = ";")

5. Procesamiento

5.1 Filtrar municipios del Putumayo

# Filtrar municipios de Putumayo por código de departamento
Putumayo <- dplyr::filter(colombiaMpios, DPTO_CCDGO == "86")

# Seleccionar columnas de interés
Municipios <- Putumayo %>% 
    select(MPIO_CCDGO, MPIO_CNMBR, AREA)

head(Municipios)

5.2 Configurar ciudades con coordenadas

# Convertir ciudades a objeto espacial
sf.cities2 <- st_as_sf(x = cities2, coords = c("lng", "lat"))

# Asignar CRS WGS84
st_crs(sf.cities2) <- 4326

# Transformar municipios al mismo CRS
Municipios <- st_transform(Municipios, crs = 4326)

# Confirmar que tengan el mismo CRS
st_crs(Municipios) == st_crs(sf.cities2)
## [1] TRUE

5.3 Filtrar ciudades del Putumayo

# Unión espacial entre ciudades y municipios
sf.cities.joined <- st_join(sf.cities2, Municipios, join = st_within)

# Filtrar ciudades del Putumayo
putumayo.cities <- dplyr::filter(sf.cities.joined, admin_name == "Putumayo")

head(putumayo.cities)

5.4 Unir frutales con municipios

# Estandarizar nombres en Municipios
Municipios$nombre_limpio <- Municipios$MPIO_CNMBR %>%
    str_to_upper() %>%
    str_trim() %>%
    iconv(to = "ASCII//TRANSLIT")

# Estandarizar nombres en frutales
frutales$nombre_limpio <- frutales$municipio %>%
    str_to_upper() %>%
    str_trim() %>%
    iconv(to = "ASCII//TRANSLIT")

# Unir por nombre limpio
munic_frutales <- left_join(Municipios, frutales,
                            by = c("nombre_limpio" = "nombre_limpio"))

# Verificar unión
head(munic_frutales %>% select(MPIO_CNMBR, municipio, grupo_especie, max_prod))

5.5 Clasificar producción en intervalos

# Calcular intervalos con método Fisher
breaks <- suppressWarnings(
    classIntervals(munic_frutales$max_prod, n = 6, style = "fisher")
)

# Crear etiquetas para los intervalos
lab_vec <- vector(length = length(breaks$brks) - 1)
rounded_breaks <- round(breaks$brks, 2)
lab_vec[1] <- paste0("[", rounded_breaks[1], " - ", rounded_breaks[2], "]")
for(i in 2:(length(breaks$brks) - 1)){
    lab_vec[i] <- paste0("(", rounded_breaks[i], " - ", rounded_breaks[i+1], "]")
}

# Agregar columna de clasificación
munic_frutales <- munic_frutales %>%
    mutate(faktor_class = factor(cut(max_prod, breaks$brks, 
                                     include.lowest = TRUE), 
                                 labels = lab_vec))
munic_frutales$Produccion <- munic_frutales$faktor_class

# Calcular centroides para etiquetas
munic_frutales$mid <- sf::st_centroid(munic_frutales$geometry)
LONG <- st_coordinates(munic_frutales$mid)[,1]
LAT  <- st_coordinates(munic_frutales$mid)[,2]

6. Mapas temáticos

6.1 Mapa coroplético con ggplot2

ggplot(data = munic_frutales) +
    geom_sf(aes(fill = Produccion)) +
    geom_label_repel(aes(x = LONG, y = LAT, label = MPIO_CNMBR),
                     label.padding = unit(0.05, "lines"),
                     label.r = unit(0.025, "lines"),
                     label.size = 0.05) +
    geom_sf(data = putumayo.cities, color = "red", size = 2) +
    scale_fill_brewer(palette = "Greens", na.value = "grey90",
                      name = "Producción (ton)") +
    labs(title = "Producción de Frutales Tropicales en Putumayo 2022",
         subtitle = "Máxima producción por municipio",
         caption = "Fuente: EVA 2022 - DANE 2018") +
    theme_minimal() +
    theme(legend.position = "right",
          plot.title = element_text(hjust = 0.5, face = "bold"),
          plot.subtitle = element_text(hjust = 0.5))

6.2 Mapa con tmap

tmap_mode("plot")
## ℹ tmap modes "plot" - "view"
## ℹ toggle with `tmap::ttm()`
tm_shape(munic_frutales) +
    tm_polygons(col = "max_prod",
                palette = "Greens",
                title = "Producción (ton)",
                style = "fisher",
                n = 6) +
    tm_shape(putumayo.cities) +
    tm_dots(col = "red", size = 0.3) +
    tm_text("city",
            size = 0.6,
            just = "bottom",
            ymod = -0.5) +
    tm_layout(title = "Frutales Tropicales - Putumayo 2022",
              title.position = c("right", "top"),
              title.size = 1,
              legend.outside = TRUE,
              frame = TRUE) +
    tm_compass(type = "arrow",
               position = c("left", "top"),
               size = 1.5) +
    tm_scalebar(position = c("right", "bottom")) +
    tm_credits("Fuente: EVA 2022 - DANE 2018",
               position = c("right", "bottom"))
## 
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_polygons()`: instead of `style = "fisher"`, use fill.scale =
## `tm_scale_intervals()`.
## ℹ Migrate the argument(s) 'style', 'n', 'palette' (rename to 'values') to
##   'tm_scale_intervals(<HERE>)'[v3->v4] `tm_polygons()`: use 'fill' for the fill color of polygons/symbols
## (instead of 'col'), and 'col' for the outlines (instead of 'border.col').[v3->v4] `tm_polygons()`: migrate the argument(s) related to the legend of the
## visual variable `fill` namely 'title' to 'fill.legend = tm_legend(<HERE>)'[v3->v4] `tm_text()`: migrate the layer options 'just' to 'options =
## opt_tm_text(<HERE>)'[v3->v4] `tm_layout()`: use `tm_title()` instead of `tm_layout(title = )`[cols4all] color palettes: use palettes from the R package cols4all. Run
## `cols4all::c4a_gui()` to explore them. The old palette name "Greens" is named
## "brewer.greens"Multiple palettes called "greens" found: "brewer.greens", "matplotlib.greens". The first one, "brewer.greens", is returned.

6.3 Mapa interactivo con leaflet

# Transformar a WGS84 (leaflet requiere lat/long, no coordenadas planas)
munic_frutales_wgs <- st_transform(munic_frutales, crs = 4326)
putumayo.cities_wgs <- st_transform(putumayo.cities, crs = 4326)

# Paleta por intervalos (bins), igual que en la imagen de referencia
bins <- c(0, 50000, 100000, 150000, 200000, Inf)
pal <- colorBin("YlOrBr", domain = munic_frutales_wgs$max_prod,
                 bins = bins, na.color = "grey70")

# Etiquetas emergentes al pasar el mouse
labels <- sprintf(
    "<strong>%s</strong><br/>Producción máxima: %s ton",
    munic_frutales_wgs$MPIO_CNMBR,
    format(munic_frutales_wgs$max_prod, big.mark = ",")
) %>% lapply(HTML)

leaflet(munic_frutales_wgs) %>%
    addProviderTiles(providers$Esri.WorldGrayCanvas) %>%
    addPolygons(
        fillColor = ~pal(max_prod),
        weight = 1,
        color = "white",
        opacity = 1,
        dashArray = "1",
        fillOpacity = 0.7,
        highlightOptions = highlightOptions(
            weight = 2, color = "#666",
            fillOpacity = 0.9, bringToFront = TRUE
        ),
        label = labels,
        labelOptions = labelOptions(
            style = list("font-weight" = "normal", padding = "3px 8px"),
            textsize = "13px", direction = "auto"
        )
    ) %>%
    addCircleMarkers(
        data = putumayo.cities_wgs,
        radius = 4,
        color = "red",
        fillColor = "red",
        fillOpacity = 1,
        stroke = FALSE,
        label = ~city
    ) %>%
    addLegend(
        pal = pal,
        values = ~max_prod,
        opacity = 0.7,
        title = "max_prod",
        position = "topright"
    ) %>%
    addScaleBar(position = "bottomleft") %>%
    addLayersControl(position = "topleft")

7. Conclusiones

8. Bibliografia

Lizarazo, I., 2022. Introducción a los mapas temáticos. Disponible en https://rpubs.com/ials2un/thematic_maps_v2.