1. Introducción

El paquete sf permite trabajar con datos geográficos vectoriales en R. En este cuaderno exploraremos los municipios del departamento del Putumayo usando los shapefiles del DANE (2018), y ubicaremos las ciudades principales del departamento usando un archivo de ciudades del mundo.

  1. Configuración

Cargamos los paquetes necesarios para el análisis:

library(sf)
library(dplyr)
library(ggplot2)
library(ggspatial)

3. Lectura de datos espaciales

3.1 Municipios y Departamentos de Colombia

Leemos los shapefiles del DANE con la información de municipios y departamentos:

colombia <- 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 1\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
colombia3 <- 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 1\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

3.2 Ciudades del mundo

Leemos el archivo de ciudades del mundo:

cities_raw <- read.csv('./Datos/WORLD_CITIES/worldcities.csv', sep = ";")
cities <- cities_raw %>%
          st_as_sf(coords = c("lng", "lat"), crs = 4326)

4. Exploración de los datos

Verificamos las columnas disponibles en cada archivo:

head(colombia[, c("DPTO_CCDGO", "MPIO_CNMBR")])

5. Selección del Putumayo

5.1 Filtrar municipios del Putumayo

Filtramos los municipios usando el código de departamento 86:

putumayo <- dplyr::filter(colombia, DPTO_CCDGO == "86")

El departamento del Putumayo tiene 13 municipios.

5.2 Mapa preliminar

Hacemos un mapa rápido para verificar la selección:

plot(st_geometry(putumayo), 
     col = sf.colors(13, categorical = TRUE), 
     border = 'grey', 
     axes = TRUE)
plot(st_geometry(st_centroid(putumayo)), 
     pch = 3, col = 'red', add = TRUE)
## Warning: st_centroid assumes attributes are constant over geometries

5.3 Guardar el Putumayo

Guardamos los municipios del Putumayo en un nuevo archivo GeoPackage:

st_write(putumayo, "putumayo.gpkg", driver = "GPKG", append = F)
## Deleting layer `putumayo' using driver `GPKG'
## Writing layer `putumayo' to data source `putumayo.gpkg' using driver `GPKG'
## Writing 13 features with 90 fields and geometry type Multi Polygon.

6. Selección de ciudades por ubicación

6.1 Verificar sistemas de referencia

Antes de hacer la selección espacial verificamos que los CRS coincidan:

st_crs(cities)$epsg
## [1] 4326
st_crs(putumayo)$epsg
## [1] 4686

Los CRS son diferentes, por lo tanto transformamos el de ciudades para que coincida con el del Putumayo:

ncities <- st_transform(cities, crs = st_crs(putumayo))

6.2 Seleccionar ciudades dentro del Putumayo

putumayo_cities <- ncities[putumayo, , op = st_within]

Se encontraron 12 ciudades dentro del departamento del Putumayo:

putumayo_cities$city
##  [1] "Puerto Asís"       "Orito"             "Mocoa"            
##  [4] "Valle del Guamuez" "La Dorada"         "Puerto Leguízamo" 
##  [7] "Puerto Guzmán"     "Villagarzón"       "Puerto Guzmán"    
## [10] "Sibundoy"          "Puerto Caicedo"    "Solita"

7. Mapas finales

7.1 Mapa básico con ggplot

ggplot() +
  geom_sf(data = putumayo) +
  geom_sf(data = putumayo_cities, aes(color = city), size = 3) +
  labs(x = "Longitud", y = "Latitud", 
       title = "Ciudades del Putumayo") +
  theme_bw()

7.2 Mapa completo con escala y flecha de norte

ggplot() +
  geom_sf(data = putumayo) +
  geom_sf(data = putumayo_cities, aes(color = city, label = city), size = 3) +
  annotation_scale(location = "tr", height = unit(.25, "cm"),
                   width = unit(1, "cm"), pad_x = unit(0.3, "in"),
                   pad_y = unit(0.5, "in")) +
  annotation_north_arrow(height = unit(1, "cm"), width = unit(1, "cm"),
                         which_north = "true", location = "tr",
                         pad_x = unit(0.5, "in"), pad_y = unit(0.05, "in")) +
  labs(x = "Longitud", y = "Latitud", 
       title = "Ciudades del Putumayo") +
  theme_bw()
## Warning in layer_sf(geom = GeomSf, data = data, mapping = mapping, stat = stat,
## : Ignoring unknown aesthetics: label
## Warning in annotation_scale(location = "tr", height = unit(0.25, "cm"), :
## Ignoring unknown parameters: `width`

8. Entorno de trabajo

sessionInfo()
## R version 4.6.0 (2026-04-24 ucrt)
## Platform: x86_64-w64-mingw32/x64
## Running under: Windows 11 x64 (build 26200)
## 
## Matrix products: default
##   LAPACK version 3.12.1
## 
## locale:
## [1] LC_COLLATE=Spanish_Colombia.utf8  LC_CTYPE=Spanish_Colombia.utf8   
## [3] LC_MONETARY=Spanish_Colombia.utf8 LC_NUMERIC=C                     
## [5] LC_TIME=Spanish_Colombia.utf8    
## 
## time zone: America/Bogota
## tzcode source: internal
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggspatial_1.1.10 ggplot2_4.0.3    dplyr_1.2.1      sf_1.1-1        
## 
## loaded via a namespace (and not attached):
##  [1] gtable_0.3.6       jsonlite_2.0.0     compiler_4.6.0     tidyselect_1.2.1  
##  [5] Rcpp_1.1.1-1.1     jquerylib_0.1.4    scales_1.4.0       yaml_2.3.12       
##  [9] fastmap_1.2.0      R6_2.6.1           generics_0.1.4     classInt_0.4-11   
## [13] s2_1.1.9           knitr_1.51         tibble_3.3.1       units_1.0-1       
## [17] DBI_1.3.0          bslib_0.10.0       pillar_1.11.1      RColorBrewer_1.1-3
## [21] rlang_1.2.0        cachem_1.1.0       xfun_0.57          sass_0.4.10       
## [25] S7_0.2.2           cli_3.6.6          withr_3.0.2        magrittr_2.0.5    
## [29] wk_0.9.5           class_7.3-23       digest_0.6.39      grid_4.6.0        
## [33] rstudioapi_0.18.0  lifecycle_1.0.5    vctrs_0.7.3        KernSmooth_2.23-26
## [37] proxy_0.4-29       evaluate_1.0.5     glue_1.8.1         farver_2.1.2      
## [41] e1071_1.7-17       rmarkdown_2.31     tools_4.6.0        pkgconfig_2.0.3   
## [45] htmltools_0.5.9