El paquete sf de R permite trabajar con el estándar de características simples (simple features, ISO 19125-1:2004), que describe cómo representar en el computador objetos del mundo real, con énfasis en su geometría espacial. Es hoy la forma más usada para manejar datos vectoriales geográficos en R, y ofrece herramientas de consulta, selección, geoprocesamiento y visualización similares a las de un SIG como QGIS o ArcGIS.
En este cuaderno se usan características simples para leer, consultar y visualizar datos geoespaciales. Se construye un mapa de los municipios del departamento de Cundinamarca con sus principales ciudades, incluyendo escala gráfica y flecha de norte.
Se sigue el cuaderno Características simples en R (Lizarazo, I.).
Prerrequisito: tener en la carpeta del proyecto el Marco Geoestadístico Nacional (MGN) del DANE a nivel municipio. Aquí se usa la versión MGN2025 en formato GeoPackage, descargada del Geoportal del DANE.
Librerías que se usan:
library(sf) # características simples
library(dplyr) # manipulación de datos
library(ggplot2) # gráficos y mapas
library(ggspatial) # escala gráfica y flecha de norte
Se busca el archivo del MGN de municipios dentro de la carpeta del
proyecto y se lee como un objeto sf:
(mgn <- list.files("MGN2025_MPIO", pattern = "\\.gpkg$", recursive = TRUE, full.names = TRUE))
## [1] "MGN2025_MPIO/MGN_ADM_MPIO_GRAFICO (Geopackage).gpkg"
colombia <- st_read(mgn[1])
## Reading layer `MGN_ADM_MPIO_GRAFICO (Geopackage)' from data source
## `C:\GEOMATICA2026\Restudio\Proyecto_ciudades\MGN2025_MPIO\MGN_ADM_MPIO_GRAFICO (Geopackage).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
Se revisan sus atributos y su sistema de referencia:
colombia
## 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...
names(colombia)
## [1] "dpto_ccdgo" "mpio_ccdgo" "mpio_cdpmp" "dpto_cnmbr" "mpio_cnmbr"
## [6] "mpio_crslc" "mpio_tipo" "mpio_narea" "mpio_nano" "shape_Leng"
## [11] "shape_Area" "geom"
st_crs(colombia)$epsg
## [1] 4326
Los departamentos que contiene:
sort(unique(colombia$dpto_cnmbr))
## [1] "AMAZONAS"
## [2] "ANTIOQUIA"
## [3] "ARAUCA"
## [4] "ARCHIPIÉLAGO DE SAN ANDRÉS, PROVIDENCIA Y SANTA CATALINA"
## [5] "ATLÁNTICO"
## [6] "BOGOTÁ, D.C."
## [7] "BOLÍVAR"
## [8] "BOYACÁ"
## [9] "CALDAS"
## [10] "CAQUETÁ"
## [11] "CASANARE"
## [12] "CAUCA"
## [13] "CESAR"
## [14] "CHOCÓ"
## [15] "CÓRDOBA"
## [16] "CUNDINAMARCA"
## [17] "GUAINÍA"
## [18] "GUAVIARE"
## [19] "HUILA"
## [20] "LA GUAJIRA"
## [21] "MAGDALENA"
## [22] "META"
## [23] "NARIÑO"
## [24] "NORTE DE SANTANDER"
## [25] "PUTUMAYO"
## [26] "QUINDÍO"
## [27] "RISARALDA"
## [28] "SANTANDER"
## [29] "SUCRE"
## [30] "TOLIMA"
## [31] "VALLE DEL CAUCA"
## [32] "VAUPÉS"
## [33] "VICHADA"
Se seleccionan los municipios de Cundinamarca usando su código DANE
(25):
(cundinamarca <- colombia %>% filter(dpto_ccdgo == "25"))
## Simple feature collection with 116 features and 11 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -74.89063 ymin: 3.730129 xmax: -73.05256 ymax: 5.837258
## Geodetic CRS: WGS 84
## First 10 features:
## dpto_ccdgo mpio_ccdgo mpio_cdpmp dpto_cnmbr mpio_cnmbr
## 1 25 001 25001 CUNDINAMARCA AGUA DE DIOS
## 2 25 019 25019 CUNDINAMARCA ALBÁN
## 3 25 035 25035 CUNDINAMARCA ANAPOIMA
## 4 25 040 25040 CUNDINAMARCA ANOLAIMA
## 5 25 053 25053 CUNDINAMARCA ARBELÁEZ
## 6 25 086 25086 CUNDINAMARCA BELTRÁN
## 7 25 095 25095 CUNDINAMARCA BITUIMA
## 8 25 099 25099 CUNDINAMARCA BOJACÁ
## 9 25 120 25120 CUNDINAMARCA CABRERA
## 10 25 123 25123 CUNDINAMARCA CACHIPAY
## mpio_crslc mpio_tipo mpio_narea mpio_nano
## 1 Ordenanza 78 Noviembre 29 de 1963 MUNICIPIO 85.88512 2024
## 2 Ordenanza 19 del 22 de Mayo de 1903 MUNICIPIO 50.78391 2024
## 3 Dispocisión de Septiembre 1 de 1864 MUNICIPIO 123.83748 2024
## 4 1882 MUNICIPIO 120.83121 2024
## 5 Decreto 32 de Enero 16 de 1886 MUNICIPIO 142.30947 2024
## 6 Ordenanza 5 del 12 de Noviembre de 1853 MUNICIPIO 176.71154 2024
## 7 1772 MUNICIPIO 60.98904 2024
## 8 1700 MUNICIPIO 102.20925 2024
## 9 Ordenanza 79 Noviembre 29 de 1963 MUNICIPIO 421.41640 2024
## 10 Ordenanza 6 Noviembre 26 de 1982 MUNICIPIO 53.39938 2024
## shape_Leng shape_Area geom
## 1 0.4963557 0.007002449 MULTIPOLYGON (((-74.67275 4...
## 2 0.5162142 0.004144411 MULTIPOLYGON (((-74.47852 4...
## 3 0.6705565 0.010100758 MULTIPOLYGON (((-74.55201 4...
## 4 0.5280079 0.009859268 MULTIPOLYGON (((-74.43043 4...
## 5 0.8065844 0.011603784 MULTIPOLYGON (((-74.42848 4...
## 6 0.9093670 0.014413273 MULTIPOLYGON (((-74.76139 4...
## 7 0.4907957 0.004976541 MULTIPOLYGON (((-74.51062 4...
## 8 0.4979169 0.008339597 MULTIPOLYGON (((-74.32819 4...
## 9 1.0188051 0.034347363 MULTIPOLYGON (((-74.46463 4...
## 10 0.4211105 0.004356744 MULTIPOLYGON (((-74.40513 4...
nrow(cundinamarca)
## [1] 116
Un mapa rudimentario de los municipios, con sus centroides en rojo:
plot(st_geometry(cundinamarca), col = sf.colors(12, categorical = TRUE),
border = "grey", axes = TRUE)
plot(st_geometry(st_centroid(cundinamarca)), pch = 3, col = "red", add = TRUE)
El hueco en el centro es Bogotá D.C., que en el MGN
es un departamento aparte (código 11).
La función st_write() guarda un objeto sf
en muchos formatos. El formato se indica con la extensión del archivo o
con el driver de GDAL. El parámetro append = FALSE
permite sobrescribir el archivo si ya existe.
Se guardan los municipios de toda Colombia y los de Cundinamarca en formato GeoPackage:
st_write(colombia, "municipios.gpkg", driver = "GPKG", append = FALSE)
## Deleting layer `municipios' using driver `GPKG'
## Writing layer `municipios' to data source `municipios.gpkg' using driver `GPKG'
## Writing 1122 features with 11 fields and geometry type Multi Polygon.
st_write(cundinamarca, "cund_munic.gpkg", driver = "GPKG", append = FALSE)
## Deleting layer `cund_munic' using driver `GPKG'
## Writing layer `cund_munic' to data source `cund_munic.gpkg' using driver `GPKG'
## Writing 116 features with 11 fields and geometry type Multi Polygon.
Se verifica que los archivos se crearon:
list.files(pattern = "gpkg")
## [1] "cund_munic.gpkg" "municipios.gpkg"
Y se vuelve a leer el GeoPackage de municipios como un objeto
sf:
colombia2 <- st_read("./municipios.gpkg")
## Reading layer `municipios' from data source
## `C:\GEOMATICA2026\Restudio\Proyecto_ciudades\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
colombia2
## 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...
Se usa la base de ciudades del mundo de simplemaps
(worldcities.csv). Es una tabla con columnas de latitud
(lat) y longitud (lng), así que se convierte
en un objeto sf de puntos con coordenadas geográficas WGS84
(EPSG 4326). Se toman solo las de Colombia:
cities <- read.csv("worldcities.csv") %>%
filter(country == "Colombia") %>%
st_as_sf(coords = c("lng", "lat"), crs = 4326)
cities
## Simple feature collection with 739 features and 9 fields
## Geometry type: POINT
## Dimension: XY
## Bounding box: xmin: -81.7006 ymin: -4.215 xmax: -67.4837 ymax: 12.5847
## Geodetic CRS: WGS 84
## First 10 features:
## city city_ascii country iso2 iso3 admin_name capital
## 1 Bogotá Bogota Colombia CO COL Bogotá primary
## 2 Cali Cali Colombia CO COL Valle del Cauca admin
## 3 Medellín Medellin Colombia CO COL Antioquia admin
## 4 Barranquilla Barranquilla Colombia CO COL Atlántico admin
## 5 Cartagena Cartagena Colombia CO COL Bolívar admin
## 6 Bucaramanga Bucaramanga Colombia CO COL Santander admin
## 7 Palermo Palermo Colombia CO COL Huila minor
## 8 Cúcuta Cucuta Colombia CO COL Norte de Santander admin
## 9 Soledad Soledad Colombia CO COL Atlántico minor
## 10 Soacha Soacha Colombia CO COL Cundinamarca minor
## population id geometry
## 1 7968095 1170483426 POINT (-74.0817 4.6097)
## 2 2916790 1170417589 POINT (-76.5197 3.44)
## 3 2490164 1170680389 POINT (-75.5676 6.2502)
## 4 1326588 1170179113 POINT (-74.8019 10.9833)
## 5 914552 1170886102 POINT (-75.5144 10.3997)
## 6 893040 1170940590 POINT (-73.1161 7.1186)
## 7 800000 1170614290 POINT (-75.4339 2.8883)
## 8 748948 1170743755 POINT (-72.5047 7.9075)
## 9 676014 1170765625 POINT (-74.7858 10.9097)
## 10 655025 1170512000 POINT (-74.2144 4.5781)
Antes de cruzar las dos capas hay que verificar que estén en el mismo sistema de referencia:
st_crs(cities)$epsg
## [1] 4326
st_crs(cundinamarca)$epsg
## [1] 4326
Se transforman las ciudades al sistema de los municipios y se seleccionan solo las que están dentro del departamento:
ncities <- st_transform(cities, crs = st_crs(cundinamarca))
cund_cities <- ncities[cundinamarca, , op = st_within]
cund_cities %>% st_drop_geometry() %>% select(city, population) %>% arrange(desc(population))
## city population
## 1 Soacha 655025
## 2 Facatativá 145080
## 3 Madrid 135000
## 4 Mosquera 128012
## 5 Chía 124309
## 6 Fusagasugá 114722
## 7 Zipaquirá 106461
## 8 Girardot 95427
## 9 Funza 90671
## 10 Cajicá 54111
## 11 Villa de San Diego de Ubaté 31042
## 12 Sibaté 23644
## 13 Silvania 22020
## 14 Cota 20462
## 15 El Rosal 18958
## 16 Tocaima 18790
## 17 Villeta 17985
## 18 Sopó 17435
## 19 La Mesa 16854
## 20 Guaduas 15862
## 21 Tocancipá 15355
## 22 Anapoima 14519
## 23 La Calera 13470
## 24 Agua de Dios 13182
## 25 Tabio 13145
## 26 La Vega 13085
## 27 Anolaima 12911
## 28 Pacho 12714
## 29 Viotá 12589
## 30 Arbeláez 12292
## 31 Fómeque 12214
## 32 Gachancipá 11252
## 33 Puerto Salgar 11082
## 34 La Palma 11012
## 35 Tenjo 10915
## 36 Yacopí 10887
## 37 Chocontá 10554
## 38 Caparrapí 10301
## 39 El Colegio 10251
## 40 Medina 10205
## 41 Sasaima 9807
## 42 Bojacá 9256
## 43 Granada 9253
## 44 Suesca 8567
## 45 Cogua 7736
## 46 Cáqueza 7297
## 47 Simijaca 7293
## 48 Ricaurte 6857
## 49 Villapinzón 6526
## 50 Susa 6315
## 51 Subachoque 6061
## 52 Nemocón 5684
## 53 Guasca 5203
## 54 Une 3938
## 55 Guachetá 3756
## 56 Gachetá 3689
## 57 Choachí 3615
## 58 Sesquilé 3468
## 59 Cachipay 3153
## 60 Pasca 2841
## 61 Carmen de Carupa 2374
## 62 Lenguazaque 2282
## 63 Ubalá 1280
## 64 Tausa 1058
## 65 San Antonio del Tequendama 1018
## 66 Junín 998
## 67 Tena 849
Se verifica con un mapa rudimentario que las ciudades seleccionadas (puntos rojos) sí caen dentro de los municipios del departamento:
plot(st_geometry(cundinamarca), col = sf.colors(12, categorical = TRUE),
border = "grey", axes = TRUE)
plot(st_geometry(cund_cities), pch = 20, col = "red", add = TRUE)
ggplot() +
# Municipios
geom_sf(data = cundinamarca, fill = "grey90", color = "grey40") +
# Ciudades
geom_sf(data = cund_cities, aes(color = city), size = 3) +
# Escala gráfica
annotation_scale(location = "bl", width_hint = 0.3) +
# Flecha de norte
annotation_north_arrow(location = "tr", which_north = "true",
height = unit(1.2, "cm"), width = unit(1.2, "cm"),
style = north_arrow_fancy_orienteering) +
# Títulos
labs(x = "Longitud", y = "Latitud",
title = "Ciudades de Cundinamarca",
color = "Ciudad",
caption = "Fuentes: DANE (MGN 2025) y simplemaps World Cities") +
guides(color = guide_legend(ncol = 2)) +
theme_bw()
sessionInfo()
## R version 4.6.1 (2026-06-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_Mexico.utf8 LC_CTYPE=Spanish_Mexico.utf8
## [3] LC_MONETARY=Spanish_Mexico.utf8 LC_NUMERIC=C
## [5] LC_TIME=Spanish_Mexico.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.11 ggplot2_4.0.3 dplyr_1.2.1 sf_1.1-3
##
## loaded via a namespace (and not attached):
## [1] gtable_0.3.6 jsonlite_2.0.0 compiler_4.6.1 tidyselect_1.2.1
## [5] Rcpp_1.1.2 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.13 knitr_1.52 tibble_3.3.1 units_1.0-1
## [17] DBI_1.3.0 bslib_0.12.0 pillar_1.11.1 RColorBrewer_1.1-3
## [21] rlang_1.3.0 cachem_1.1.0 xfun_0.62 sass_0.4.10
## [25] S7_0.2.2 cli_3.6.6 withr_3.0.3 magrittr_2.0.5
## [29] wk_0.9.5 class_7.3-23 digest_0.6.39 grid_4.6.1
## [33] rstudioapi_0.19.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.32 tools_4.6.1 pkgconfig_2.0.3
## [45] htmltools_0.5.9