Lectura de datos espaciales

Lo primero que haremos serĂĄ instalar las librerĂ­as necesarias para este cuaderno

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(ggplot2)
library(ggspatial)
getwd()
## [1] "C:/Users/isabe/OneDrive/Documentos/GB2/proyecto3"

El sigiente paso es definir el directorio de trabajo

list.files("D:\\GB2\\proyecto3\\MGN2023_MPIO_POLITICO")
## [1] "MGN_ADM_MPIO_GRAFICO.cpg"     "MGN_ADM_MPIO_GRAFICO.dbf"    
## [3] "MGN_ADM_MPIO_GRAFICO.prj"     "MGN_ADM_MPIO_GRAFICO.sbn"    
## [5] "MGN_ADM_MPIO_GRAFICO.sbx"     "MGN_ADM_MPIO_GRAFICO.shp"    
## [7] "MGN_ADM_MPIO_GRAFICO.shp.xml" "MGN_ADM_MPIO_GRAFICO.shx"
colombia <- st_read("D:\\GB2\\proyecto3\\MGN2023_MPIO_POLITICO\\MGN_ADM_MPIO_GRAFICO.shp")
## Reading layer `MGN_ADM_MPIO_GRAFICO' from data source 
##   `D:\GB2\proyecto3\MGN2023_MPIO_POLITICO\MGN_ADM_MPIO_GRAFICO.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 1121 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:  MAGNA-SIRGAS
head(colombia)

Escogemos la extensiĂłn de los archivos que utiizaremos

st_write(colombia, "municipios.gpkg", driver = "GPKG", append = F)
## Deleting layer `municipios' using driver `GPKG'
## Writing layer `municipios' to data source `municipios.gpkg' using driver `GPKG'
## Writing 1121 features with 11 fields and geometry type Multi Polygon.
list.files(pattern = "gpkg")
## [1] "municipios.gpkg"          "municipios__9377.gpkg"   
## [3] "MunicipiosSantander.gpkg" "stder_munic.gpkg"
colombia2 <- st_read(".\\municipios__9377.gpkg")
## Reading layer `muncipios9377' from data source 
##   `C:\Users\isabe\OneDrive\Documentos\GB2\proyecto3\municipios__9377.gpkg' 
##   using driver `GPKG'
## Simple feature collection with 87 features and 12 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 4828392 ymin: 2188513 xmax: 5053451 ymax: 2455407
## Projected CRS: MAGNA-SIRGAS 2018 / Origen-Nacional

Ahora seleccionaremos objetos, en este caso, los datos del departamento de Santander

(santander <- dplyr::filter(colombia, dpto_cnmbr=="SANTANDER"))

Con la siguiente funciĂłn visualizaremos un mapa rudimentario de los municipios de Santander

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

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

Vamos a subir un archivo que contenga los nombres de ciudades a nivel mundial

cities = read.csv("D:\\GB2\\proyecto3\\Datos\\worldcities.csv") %>% st_as_sf(coords=c("lng", "lat"), crs= 4326)
cities

Convertimos el sistema de coordenadas

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

Filtranos las ciudades de Santander

ncities <- st_transform(cities,crs = st_crs(santander))
stder_cities <- ncities[santander, , op = st_within]

Repetimos el mapa

plot(st_geometry(santander), col = sf.colors(12, categorical = TRUE), border = 'grey', axes = TRUE)
plot(st_geometry(stder_cities), pch = 20, col = 'red' , add =  TRUE)

Vamos a ‘plottear con elegancia’

ggplot() + geom_sf(data = santander) + geom_sf(data = stder_cities, aes(color = city, label = city), size = 3) + labs(x = "Longitud", y = "Latitud", title = "Ciudades de Santander") + theme_bw()
## Warning in layer_sf(geom = GeomSf, data = data, mapping = mapping, stat = stat,
## : Ignoring unknown aesthetics: label

Por Ășltimo, le ponemos una flecha norte a nuetro mapa

ggplot() +
geom_sf(data = santander) +
geom_sf(data = stder_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 de Santander") +
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`

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