En el presente cuaderno veremos como generar un mapa del departamento del Huila utilizando funciones de librerias del tidyverse y explicando a detalle paso por paso, en sintesis, nos familiarizaremos con Rstudio construyendo mapas cada uno mas detallado que el anterior y aprenderemos alguans funciones de las diferentes librerias y sus usos.
En primer lugar llamaremos a las librerias que vamos a utilizar, para este cuaderno emplearemos las librerias sf (simple features), dplyr, ggplot2 y ggspatial.
library(sf)
library(dplyr)
library(ggplot2)
library(ggspatial)
Posteriormente, buscaremos la ubicación de nuestra carpeta con el shapefile de los municipios de colombia descargados del DANE, haremos uso de la función “list.files()”.
list.files("C:/Users/TEMP/Downloads/GB2-20250527T194536Z-1-001/GB2/P1/DATOS/MUNICIPIOS")
## [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"
## [9] "Municipios.gpkg" "Municipios_poblacion.gpkg"
## [11] "Municipios_poblacion.gpkg-shm" "Municipios_poblacion.gpkg-wal"
la funcion “st_read()” nos permite leer el archivo shapefile y luego poderlo asignar a una variable que llamaremos “colombia”, lo asignamos con “<-”.
colombia <- st_read("C:/Users/TEMP/Downloads/GB2-20250527T194536Z-1-001/GB2/P1/DATOS/MUNICIPIOS/MGN_ADM_MPIO_GRAFICO.shp")
## Reading layer `MGN_ADM_MPIO_GRAFICO' from data source
## `C:\Users\TEMP\Downloads\GB2-20250527T194536Z-1-001\GB2\P1\DATOS\MUNICIPIOS\MGN_ADM_MPIO_GRAFICO.shp'
## using driver `ESRI Shapefile'
## Simple feature collection with 1121 features and 12 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -81.73562 ymin: -4.229406 xmax: -66.84722 ymax: 13.39473
## Geodetic CRS: MAGNA-SIRGAS
La función “head()”, nos mostrara los 6 primeros datos de la variable “colombia” que ya habiamos asignado, si quisieramos ver los ultimos 6 datos de la variable podriamos emplear la funcion “tail()”, pero en este caso nos interesa observar los primeros 6.
head(colombia)
Con la función “st_write()” crearemos un geopackage con los datos anteriormente seleccionados y le asignaremos el nombre de “municipiosR.gpkg”
st_write(colombia, "municipiosR.gpkg", driver = "GPKG", append = F)
## Deleting layer `municipiosR' using driver `GPKG'
## Writing layer `municipiosR' to data source `municipiosR.gpkg' using driver `GPKG'
## Writing 1121 features with 12 fields and geometry type Multi Polygon.
Nuevamente con “list.files()”, buscaremos los archivos gpkg dentro de la carpeta en la que estamos trabajando.
list.files(pattern="gpkg")
## [1] "huila_munic.gpkg" "municipiosR.gpkg"
De nuevo, emplearemos la función “st_read()” para asignarle la información a una nueva variable que llamaremos “colombia2”.
colombia2 <- st_read("C:/Users/TEMP/Downloads/GB2-20250527T194536Z-1-001/GB2/P1/DATOS/MUNICIPIOS/municipios.gpkg")
## Reading layer `Municipios' from data source
## `C:\Users\TEMP\Downloads\GB2-20250527T194536Z-1-001\GB2\P1\DATOS\MUNICIPIOS\Municipios.gpkg'
## using driver `GPKG'
## Simple feature collection with 37 features and 20 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -76.62466 ymin: 1.552125 xmax: -74.41303 ymax: 3.843208
## Geodetic CRS: MAGNA-SIRGAS
Llamando a la libreria dplyr, filtraremos la información de la variable colombia por el nombre del departamento, en nuestro caso “HUILA” con la función “filter()” y se la asignamos a una nueva variable que llamaremos “huila”.
huila <- dplyr::filter(colombia, dpto_cnmbr == "HUILA")
Empleando una vez más la función “st_write()”, crearemos un geopackage de la variable “huila” que se llame huila_munic.gpkg.
st_write(huila, "huila_munic.gpkg", driver = "GPKG", append = F )
## Deleting layer `huila_munic' using driver `GPKG'
## Writing layer `huila_munic' to data source `huila_munic.gpkg' using driver `GPKG'
## Writing 37 features with 12 fields and geometry type Multi Polygon.
Posteriormente, leeremos y cargaremos los datos de un documento csv que descargamos de world cities y se le asignara la información a una variable que llamaremos “cities”. Para leer el documento se usara la función “read.csv()”.
cities = read.csv("C:/Users/TEMP/Downloads/GB2-20250527T194536Z-1-001/GB2/P1/simplemaps_worldcities_basicv1.77/worldcities.csv") %>%
st_as_sf(coords=c("lng", "lat"), crs=4326)
Llamaremos la variable para visualizar su información, para esto se puede escribir el nombre de la variable en el cuadro de código
cities
Usaremos la función “st_crs()” para que nos diga el codigó del sistema de referencia de coordenadas EPSG en el que esta la variable “cities”.
st_crs(cities)$epsg
## [1] 4326
Nuevamente, usaremos la función “st_crs()” para que nos diga el codigó del sistema de referencia de coordenadas EPSG en el que esta la variable “huila”.
st_crs(huila)$epsg
## [1] 4686
Ya que ambos tienen un código EPSG diferente, Transformaremos el EPSG de la variable “cities” al mismo codigó en el que esta la variable “huila” con la función “st_transform()”y lo asignaremos a una nueva variable llamada “ncities”.
ncities <- st_transform(cities, crs= st_crs(huila))
Integraremos la variable “ncities” con la de “huila_cities” y verificaremos si la geometria de ambas variables coinciden y se encuentra una dentro de otra.
huila_cities <- ncities[huila, , op = st_within]
Utilizaremos la función “Plot()” para generar un mapa simple de nuestro departamento que incluya coordenadas y que contenga puntos que referencien la ubicación de los municipios dentro del mapa.
plot(st_geometry(huila), col = sf.colors(12, categorical = TRUE), border = 'grey', axes = TRUE)
plot(st_geometry(huila_cities), pch = 20, col = 'red', add = TRUE)
Añadiremos titulos de los ejes (latitud y longitud) y una lista de los municipios diferenciando los puntos por medio de diferentes colores a cada uno de ellos y con sus respectivos nombres, para poder generar este mapa emplearemos funciones de la libreria “ggplot2”, las cuales son “geom_sf()” y “labs()”.
ggplot() +
geom_sf(data = huila) +
geom_sf(data = huila_cities, aes(color = city, label = city), size = 3) +
labs(x = "Longitud", y = "Latitud", title = "Ciudades del Huila") +
theme_bw()
## Warning in layer_sf(geom = GeomSf, data = data, mapping = mapping, stat = stat,
## : Ignoring unknown aesthetics: label
Por ultimo, haremos un mapa más detallado y ordenado que incluye todo lo del mapa anterior pero añadiendo una escala y una estrella del norte para obtener un mapa más completo y prolijo; para esto hacemos volvemos a hacer uso de la funciones “geom_sf()” y “labs()”, y esta vez de las funciones “annotation_scale()” y “annotation_north_arrow()”.
ggplot()+
geom_sf(data = huila)+
geom_sf(data = huila_cities, aes(color = city, label = city), size =3) +
annotation_scale(location ="tr", height = unit(.25, "cm"),
with = unit(1, "cm"), pad_x = unit(0.2, "in"),
pad_y = unit(3.7, "in")) +
annotation_north_arrow(height = unit (1, "cm"), with = unit(1, "cm"),
which_north = "true", location = "tr",
pad_x = unit(3, "in"), pad_y = unit(0.12, "in")) +
labs(x= "longitud", y = "latitud", title = "Ciudades del Huila") +
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: `with`
## Warning in annotation_north_arrow(height = unit(1, "cm"), with = unit(1, :
## Ignoring unknown parameters: `with`
Para obtener información adicional que puede resultar importante empleamos la función “sessionInfo()”, la cual nos detalla desde nuestra version de RStudio hasta nuestra versión de windows o el sistema operativo con el que se halla trabajado el cuaderno.
sessionInfo()
## R version 4.5.0 (2025-04-11 ucrt)
## Platform: x86_64-w64-mingw32/x64
## Running under: Windows 11 x64 (build 26100)
##
## 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.9 ggplot2_3.5.2 dplyr_1.1.4 sf_1.0-21
##
## loaded via a namespace (and not attached):
## [1] gtable_0.3.6 jsonlite_2.0.0 compiler_4.5.0 tidyselect_1.2.1
## [5] Rcpp_1.0.14 jquerylib_0.1.4 scales_1.4.0 yaml_2.3.10
## [9] fastmap_1.2.0 R6_2.6.1 generics_0.1.4 classInt_0.4-11
## [13] s2_1.1.9 knitr_1.50 tibble_3.2.1 units_0.8-7
## [17] DBI_1.2.3 bslib_0.9.0 pillar_1.10.2 RColorBrewer_1.1-3
## [21] rlang_1.1.6 cachem_1.1.0 xfun_0.52 sass_0.4.10
## [25] cli_3.6.5 withr_3.0.2 magrittr_2.0.3 wk_0.9.4
## [29] class_7.3-23 digest_0.6.37 grid_4.5.0 rstudioapi_0.17.1
## [33] lifecycle_1.0.4 vctrs_0.6.5 KernSmooth_2.23-26 proxy_0.4-27
## [37] evaluate_1.0.3 glue_1.8.0 farver_2.1.2 e1071_1.7-16
## [41] rmarkdown_2.29 tools_4.5.0 pkgconfig_2.0.3 htmltools_0.5.8.1