Mapas de la producción agrícola

1. Introducción

Este cuaderno explica cómo hacer mapas temáticos para la producción agrícola. Para ello necesitamos dos archivos para empezar: un archivo CSV con los datos de la producción agrícola por municipio (EVA 2020) y un geopackage con los municipios de nuestro departamento de estudio. Más adelante usaremos un archivo con las vías de los municipios.

2. Preparación

Requerimos tener instaladas las librerías y cargarlas: dplyr, tmap y sf.

library(dplyr)
Warning: package 'dplyr' was built under R version 4.6.2

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(tmap)
Warning: package 'tmap' was built under R version 4.6.2
library(sf)
Warning: package 'sf' was built under R version 4.6.2
Linking to GEOS 3.14.1, GDAL 3.12.1, PROJ 9.7.1; sf_use_s2() is TRUE

3. Lectura de los archivos de los municipios y cultivos

Para este cuaderno trabajaremos con el departamento de Cundinamarca. Antes de empezar, trabajaremos en el folder /GEOMATICA2026/Proyecto_Cundinamarca_Restudio, en donde se encuentran nuestros archivos a analizar: el geopackage con los municipios y el archivo CSV con la EVA 2020 con las estadísticas de los cultivos.

list.files()
[1] "CVS.xlsx"                                   
[2] "Frutales.csv"                               
[3] "hotosm_col_roads_osm_gpkg"                  
[4] "hotosm_col_roads_osm_gpkg.zip"              
[5] "Mapas_Agricultura_EVA_Cundinamarca--1-.html"
[6] "Mapas_Agricultura_EVA_Cundinamarca--1-.Rmd" 
[7] "Mapas_Agricultura_EVA_Cundinamarca (1).Rmd" 
[8] "municipios.gpkg"                            
[9] "roads.gpkg"                                 

Ahora procedemos a leer y cargar el archivo csv

frutales <- read.csv("Frutales.csv", sep = ",", fileEncoding = "latin1", check.names = FALSE)

Y cargamos los municipios del Geopackage

(municipios = st_read('municipios.gpkg'))
Reading layer `municipios' from data source 
  `C:\GEOMATICA2026\Proyecto_Cundinamarca_Restudio\municipios.gpkg' 
  using driver `GPKG'
Simple feature collection with 1122 features and 11 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -81.73562 ymin: -4.229406 xmax: -66.84722 ymax: 13.39473
Geodetic CRS:  WGS 84
Simple feature collection with 1122 features and 11 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -81.73562 ymin: -4.229406 xmax: -66.84722 ymax: 13.39473
Geodetic CRS:  WGS 84
First 10 features:
   dpto_ccdgo mpio_ccdgo mpio_cdpmp dpto_cnmbr  mpio_cnmbr
1          05        001      05001  ANTIOQUIA    MEDELLÍN
2          05        002      05002  ANTIOQUIA   ABEJORRAL
3          05        004      05004  ANTIOQUIA    ABRIAQUÍ
4          05        021      05021  ANTIOQUIA  ALEJANDRÍA
5          05        030      05030  ANTIOQUIA       AMAGÁ
6          05        031      05031  ANTIOQUIA      AMALFI
7          05        034      05034  ANTIOQUIA       ANDES
8          05        036      05036  ANTIOQUIA ANGELÓPOLIS
9          05        038      05038  ANTIOQUIA   ANGOSTURA
10         05        040      05040  ANTIOQUIA       ANORÍ
                             mpio_crslc mpio_tipo mpio_narea mpio_nano
1                                  1965 MUNICIPIO  374.74148      2025
2                                  1814 MUNICIPIO  506.95978      2024
3                                  1912 MUNICIPIO  296.97419      2025
4     Decreto departamental 304 de 1907 MUNICIPIO  128.85643      2024
5                                  1912 MUNICIPIO   84.11714      2024
6                                  1843 MUNICIPIO 1208.34619      2025
7                                  1853 MUNICIPIO  402.45060      2024
8  Ordenanza 16 del 12 de julio de 1896 MUNICIPIO   81.86177      2024
9                                  1821 MUNICIPIO  338.36185      2024
10                                 1821 MUNICIPIO 1412.95696      2024
   shape_Leng  shape_Area                           geom
1   1.0353795 0.030607649 MULTIPOLYGON (((-75.4857 6....
2   1.1585036 0.041383896 MULTIPOLYGON (((-75.46938 5...
3   0.8106670 0.024253315 MULTIPOLYGON (((-76.09047 6...
4   0.7051995 0.010534527 MULTIPOLYGON (((-75.0332 6....
5   0.4455330 0.006866507 MULTIPOLYGON (((-75.67587 6...
6   2.0584824 0.098921100 MULTIPOLYGON (((-74.91364 7...
7   1.1469836 0.032816580 MULTIPOLYGON (((-75.86822 5...
8   0.4274956 0.006683387 MULTIPOLYGON (((-75.69149 6...
9   0.9164653 0.027679560 MULTIPOLYGON (((-75.27173 6...
10  1.8476441 0.115706037 MULTIPOLYGON (((-74.90935 7...

Para poder analizar los datos de la producción de los frutales y los datos de los municipios haremos un join; para eso, los datos deben estar en el mismo formato.

class(municipios$mpio_cdpmp)
[1] "character"
(stder.crs <- sf::st_crs(municipios))
Coordinate Reference System:
  User input: WGS 84 
  wkt:
GEOGCRS["WGS 84",
    ENSEMBLE["World Geodetic System 1984 ensemble",
        MEMBER["World Geodetic System 1984 (Transit)"],
        MEMBER["World Geodetic System 1984 (G730)"],
        MEMBER["World Geodetic System 1984 (G873)"],
        MEMBER["World Geodetic System 1984 (G1150)"],
        MEMBER["World Geodetic System 1984 (G1674)"],
        MEMBER["World Geodetic System 1984 (G1762)"],
        MEMBER["World Geodetic System 1984 (G2139)"],
        MEMBER["World Geodetic System 1984 (G2296)"],
        ELLIPSOID["WGS 84",6378137,298.257223563,
            LENGTHUNIT["metre",1]],
        ENSEMBLEACCURACY[2.0]],
    PRIMEM["Greenwich",0,
        ANGLEUNIT["degree",0.0174532925199433]],
    CS[ellipsoidal,2],
        AXIS["geodetic latitude (Lat)",north,
            ORDER[1],
            ANGLEUNIT["degree",0.0174532925199433]],
        AXIS["geodetic longitude (Lon)",east,
            ORDER[2],
            ANGLEUNIT["degree",0.0174532925199433]],
    USAGE[
        SCOPE["Horizontal component of 3D system."],
        AREA["World."],
        BBOX[-90,-180,90,180]],
    ID["EPSG",4326]]

4. Vías de Colombia

Vamos a añadir las vías de los municipios. Para ello descargamos los datos en un geopackage de la siguiente página https://data.humdata.org/dataset/hotosm_col_roads, lo guardamos en el directorio de trabajo y, usando la librería sf, filtraremos para obtener solo las vías de nuestro interés.

list.files('roads')
character(0)
(sf.roads = st_read('roads.gpkg'))
Reading layer `roads' from data source 
  `C:\GEOMATICA2026\Proyecto_Cundinamarca_Restudio\roads.gpkg' 
  using driver `GPKG'
Simple feature collection with 1162221 features and 20 fields
Geometry type: GEOMETRY
Dimension:     XY
Bounding box:  xmin: -81.73539 ymin: -4.245657 xmax: -66.84404 ymax: 15.79745
Geodetic CRS:  WGS 84
Simple feature collection with 1162221 features and 20 fields
Geometry type: GEOMETRY
Dimension:     XY
Bounding box:  xmin: -81.73539 ymin: -4.245657 xmax: -66.84404 ymax: 15.79745
Geodetic CRS:  WGS 84
First 10 features:
               id      name name_en name_es      highway surface smoothness
1  way/1346185848      <NA>    <NA>    <NA>      service    <NA>       <NA>
2  way/1427548589      <NA>    <NA>    <NA>  residential    <NA>       <NA>
3   way/500032207  Calle 11    <NA>    <NA>  residential    <NA>       <NA>
4   way/990914446      <NA>    <NA>    <NA> unclassified    <NA>       <NA>
5   way/819252847      <NA>    <NA>    <NA> unclassified    <NA>       <NA>
6   way/819256400 Carrera 7    <NA>    <NA>  residential    <NA>       <NA>
7  way/1541081892      <NA>    <NA>    <NA>        track unpaved       <NA>
8   way/819252845      <NA>    <NA>    <NA> unclassified    <NA>       <NA>
9  way/1541056193      <NA>    <NA>    <NA>        track    <NA>       <NA>
10  way/816611090      <NA>    <NA>    <NA> unclassified    <NA>       <NA>
   width lanes oneway bridge layer           source adm0_pcode adm0_name
1   <NA>  <NA>   <NA>   <NA>  <NA>             <NA>        COL  Colombia
2   <NA>  <NA>   <NA>   <NA>  <NA>             <NA>        COL  Colombia
3   <NA>  <NA>   <NA>   <NA>  <NA> Bing Aerial Maps        COL  Colombia
4   <NA>  <NA>   <NA>   <NA>  <NA>             <NA>        COL  Colombia
5   <NA>  <NA>   <NA>   <NA>  <NA>             <NA>        COL  Colombia
6   <NA>  <NA>   <NA>   <NA>  <NA> Bing Aerial Maps        COL  Colombia
7   <NA>  <NA>   <NA>   <NA>  <NA>             <NA>        COL  Colombia
8   <NA>  <NA>   <NA>   <NA>  <NA>             <NA>        COL  Colombia
9   <NA>  <NA>   <NA>    yes     1             <NA>        COL  Colombia
10  <NA>  <NA>   <NA>   <NA>  <NA>             <NA>        COL  Colombia
   adm1_pcode    adm1_name adm2_pcode adm2_name name_latin
1        CO25 Cundinamarca    CO25772    Suesca       <NA>
2        CO25 Cundinamarca    CO25772    Suesca       <NA>
3        CO25 Cundinamarca    CO25772    Suesca   Calle 11
4        CO25 Cundinamarca    CO25772    Suesca       <NA>
5        CO25 Cundinamarca    CO25772    Suesca       <NA>
6        CO25 Cundinamarca    CO25772    Suesca  Carrera 7
7        CO25 Cundinamarca    CO25772    Suesca       <NA>
8        CO25 Cundinamarca    CO25772    Suesca       <NA>
9        CO25 Cundinamarca    CO25772    Suesca       <NA>
10       CO25 Cundinamarca    CO25426   Machetá       <NA>
                             geom
1  LINESTRING (-73.80011 5.105...
2  LINESTRING (-73.79244 5.105...
3  LINESTRING (-73.80065 5.105...
4  LINESTRING (-73.7865 5.1058...
5  LINESTRING (-73.78618 5.105...
6  LINESTRING (-73.80092 5.106...
7  LINESTRING (-73.77264 5.106...
8  LINESTRING (-73.78771 5.106...
9  LINESTRING (-73.75355 5.105...
10 LINESTRING (-73.59823 5.096...

Se puede observar que estos vectores son de tipo de geometría LINESTRING, un tipo de geometría que representa una línea formada por una secuencia de puntos conectados (vértices). Es el tipo que se usa para los elementos lineales, y hay 1.162.221 registros u objetos espaciales (organizados en 20 campos de atributos), por lo que vamos a filtrar solo los datos que necesitamos.

Cambiamos los datos para que los municipios y las vías tengan el mismo CRS

nroads <- st_transform(sf.roads, crs = stder.crs)

Aplicamos el filtro (el valor CO25 varía de departamento en departamento)

(stder.roads.tmp = dplyr::filter(nroads, adm1_pcode == "CO25"))
Simple feature collection with 103032 features and 20 fields
Geometry type: GEOMETRY
Dimension:     XY
Bounding box:  xmin: -74.88107 ymin: 3.782058 xmax: -73.05464 ymax: 5.802234
Geodetic CRS:  WGS 84
First 10 features:
               id      name name_en name_es      highway surface smoothness
1  way/1346185848      <NA>    <NA>    <NA>      service    <NA>       <NA>
2  way/1427548589      <NA>    <NA>    <NA>  residential    <NA>       <NA>
3   way/500032207  Calle 11    <NA>    <NA>  residential    <NA>       <NA>
4   way/990914446      <NA>    <NA>    <NA> unclassified    <NA>       <NA>
5   way/819252847      <NA>    <NA>    <NA> unclassified    <NA>       <NA>
6   way/819256400 Carrera 7    <NA>    <NA>  residential    <NA>       <NA>
7  way/1541081892      <NA>    <NA>    <NA>        track unpaved       <NA>
8   way/819252845      <NA>    <NA>    <NA> unclassified    <NA>       <NA>
9  way/1541056193      <NA>    <NA>    <NA>        track    <NA>       <NA>
10  way/816611090      <NA>    <NA>    <NA> unclassified    <NA>       <NA>
   width lanes oneway bridge layer           source adm0_pcode adm0_name
1   <NA>  <NA>   <NA>   <NA>  <NA>             <NA>        COL  Colombia
2   <NA>  <NA>   <NA>   <NA>  <NA>             <NA>        COL  Colombia
3   <NA>  <NA>   <NA>   <NA>  <NA> Bing Aerial Maps        COL  Colombia
4   <NA>  <NA>   <NA>   <NA>  <NA>             <NA>        COL  Colombia
5   <NA>  <NA>   <NA>   <NA>  <NA>             <NA>        COL  Colombia
6   <NA>  <NA>   <NA>   <NA>  <NA> Bing Aerial Maps        COL  Colombia
7   <NA>  <NA>   <NA>   <NA>  <NA>             <NA>        COL  Colombia
8   <NA>  <NA>   <NA>   <NA>  <NA>             <NA>        COL  Colombia
9   <NA>  <NA>   <NA>    yes     1             <NA>        COL  Colombia
10  <NA>  <NA>   <NA>   <NA>  <NA>             <NA>        COL  Colombia
   adm1_pcode    adm1_name adm2_pcode adm2_name name_latin
1        CO25 Cundinamarca    CO25772    Suesca       <NA>
2        CO25 Cundinamarca    CO25772    Suesca       <NA>
3        CO25 Cundinamarca    CO25772    Suesca   Calle 11
4        CO25 Cundinamarca    CO25772    Suesca       <NA>
5        CO25 Cundinamarca    CO25772    Suesca       <NA>
6        CO25 Cundinamarca    CO25772    Suesca  Carrera 7
7        CO25 Cundinamarca    CO25772    Suesca       <NA>
8        CO25 Cundinamarca    CO25772    Suesca       <NA>
9        CO25 Cundinamarca    CO25772    Suesca       <NA>
10       CO25 Cundinamarca    CO25426   Machetá       <NA>
                             geom
1  LINESTRING (-73.80011 5.105...
2  LINESTRING (-73.79244 5.105...
3  LINESTRING (-73.80065 5.105...
4  LINESTRING (-73.7865 5.1058...
5  LINESTRING (-73.78618 5.105...
6  LINESTRING (-73.80092 5.106...
7  LINESTRING (-73.77264 5.106...
8  LINESTRING (-73.78771 5.106...
9  LINESTRING (-73.75355 5.105...
10 LINESTRING (-73.59823 5.096...

Seleccionamos las columnas importantes

stder.roads.tmp %>% select('id', 'name', 'highway', 'adm2_pcode', 'adm2_name') -> stder.roads

5. Unir los datos

Tenemos que asegurarnos de que los datos que vamos a unir sean del mismo tipo. Además, vamos a usar la librería janitor para ajustar y limpiar nuestros datos para que no ocurran errores, y usamos stringr para que los códigos de los municipios sean iguales. Aplicamos filtros y realizamos el join.

library(janitor)
Warning: package 'janitor' was built under R version 4.6.2

Adjuntando el paquete: 'janitor'
The following objects are masked from 'package:stats':

    chisq.test, fisher.test
library(stringr)
Warning: package 'stringr' was built under R version 4.6.2
# Limpiar nombres de columnas
frutales <- clean_names(frutales)

# Asegurar que la producción sea numérica
frutales <- frutales %>%
  mutate(produccion = as.numeric(produccion))

# Asegurar que el código DANE tenga 5 dígitos ("25XXX" para Cundinamarca)
frutales <- frutales %>%
  mutate(mpio_cdpmp = sprintf("%05d", as.numeric(codigo_dane_municipio)))

# Dejar solo los registros de Cundinamarca y del grupo Frutales
frutales <- frutales %>%
  filter(startsWith(mpio_cdpmp, "25")) %>%
  filter(tolower(trimws(grupo_cultivo)) == "frutales")

# Dejar el cultivo de mayor producción de cada municipio (una fila por municipio)
frutales <- frutales %>%
  group_by(mpio_cdpmp) %>%
  slice_max(order_by = produccion, n = 1, with_ties = FALSE) %>%
  ungroup()

# Filtrar SOLO los municipios de Cundinamarca (cuyo código DANE inicia por "25")
municipios_cundinamarca <- municipios %>%
  filter(startsWith(as.character(mpio_cdpmp), "25"))

# Realizar el join solo con los municipios de Cundinamarca
munic_frutales <- left_join(municipios_cundinamarca, frutales, by = "mpio_cdpmp")

munic_frutales <- munic_frutales %>%
  mutate(etiqueta_mapa = ifelse(is.na(cultivo),
                                mpio_cnmbr,
                                paste0(mpio_cnmbr, "\n(", cultivo, ")")))

Como mejora, separamos también las vías principales (autopistas, troncales, primarias, secundarias y terciarias). Así el mapa no se llena de calles y caminos pequeños y se pueden leer mejor los municipios y sus datos.

stder.roads.principales <- stder.roads %>%
  filter(highway %in% c("motorway", "trunk", "primary", "secondary", "tertiary"))

6. Creación del mapa

Para crear el mapa debemos indicar las diferentes capas y objetos que vamos a utilizar en nuestro mapa.

frutales_map2 =
  # CAPA 1: Municipios de Cundinamarca con Producción
  tm_shape(munic_frutales) +
  # Se quita tm_view para que encuadre automáticamente en Cundinamarca
  tm_polygons(
    fill = "produccion",
    fill.scale = tm_scale_intervals(
      style = "jenks",
      n = 8),
    fill.legend = tm_legend(title = "Producción (t)")
  ) +
  tm_text(
    text = "mpio_cnmbr",
    size = 0.50,
    fontfamily = "sans",
    col = "#222222",
    alpha = 0.85
  ) +

  # CAPA 2: Vías principales de Cundinamarca
  tm_shape(stder.roads.principales) +
  tm_lines(col = "darkgrey", lwd = 1.2, lty = "solid") +

  # COMPONENTES DEL MAPA
  tm_credits("Fuente: UPRA (2020)", fontface = "bold") +
  tm_title("Producción de frutales en Cundinamarca (2020)",
           fontface = "bold.italic",
           fontfamily = "monospace") +
  tm_scalebar(position = c("left", "bottom"))
── tmap v3 code detected ───────────────────────────────────────────────────────

Ahora el mapa con el cultivo que hay en el departamento

frutales_map3 =
  # CAPA 1: Municipios de Cundinamarca
  tm_shape(munic_frutales) +
  tm_polygons(
    fill = "produccion",
    fill.scale = tm_scale_intervals(
      style = "jenks",
      n = 8),
    fill.legend = tm_legend(title = "Producción (t)")
  ) +
  # ETIQUETAS: Muestra el cultivo principal de cada municipio
  tm_text(
    text = "cultivo",  # Muestra el cultivo principal
    size = 0.45,       # Reducido ligeramente para evitar amontonamiento
    fontfamily = "sans",
    col = "#222222",
    alpha = 0.85
  ) +

  # CAPA 2: Vías principales
  tm_shape(stder.roads.principales) +
  tm_lines(col = "darkgrey", lwd = 1.2, lty = "solid") +

  # COMPONENTES DEL MAPA
  tm_credits("Fuente: UPRA (2020)", fontface = "bold") +
  tm_title("Cultivo principal y producción de frutales en Cundinamarca",
           fontface = "bold.italic",
           fontfamily = "monospace") +
  tm_scalebar(position = c("left", "bottom"))

Ahora visualizamos el mapa creado

frutales_map2
Warning in graphics::strwidth(comp$text, units = "inch", family =
comp$fontfamily, : font family not found in Windows font database
Warning in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
font family not found in Windows font database

frutales_map3
Warning in graphics::strwidth(comp$text, units = "inch", family =
comp$fontfamily, : font family not found in Windows font database
Warning in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
font family not found in Windows font database

7. Referencias