Cargando las librerias correspondientes:
library(sf)
library(dplyr)
library(ggplot2)
library(ggspatial)
Definiendo rutas dentro del directorio de trabajo:
# Ponemos a R en nuestro archivo correspondiente
setwd("C:/Users/pc/OneDrive/Documentos/GB2/RSTUDIO/cuaderno3")
# Definimos ruta
dane <- "C:\\Users\\pc\\OneDrive\\Documentos\\GB2\\RSTUDIO\\datos_necesarios\\MGN2025_MPIO_GRAFICO\\MGN_ADM_MPIO_GRAFICO.shp"
# Definimos ruta
cities <- "C:\\Users\\pc\\OneDrive\\Documentos\\GB2\\RSTUDIO\\datos_necesarios\\WORDCITIES\\worldcities.csv"
Aqui leermos el SHP con la informacion correspondiente
# Asignando los datos en la variable
colombia <- st_read(dane) 
## Reading layer `MGN_ADM_MPIO_GRAFICO' from data source 
##   `C:\Users\pc\OneDrive\Documentos\GB2\RSTUDIO\datos_necesarios\MGN2025_MPIO_GRAFICO\MGN_ADM_MPIO_GRAFICO.shp' 
##   using driver `ESRI Shapefile'
## 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
# Asignando los datos en la variable 
cities_tabla <- read.csv(cities)
Exportaremos los datos en formato GPKG para poder visualizar los municipios de colombia y asi utilizar la libreria (dplyr) y realizar el analisis correspondiente.
# Funcion para exportar los datos ouput 
st_write(colombia, "municipos.gpkg", driver = "GPKG", append = F)
## Deleting layer `municipos' using driver `GPKG'
## Writing layer `municipos' to data source `municipos.gpkg' using driver `GPKG'
## Writing 1122 features with 11 fields and geometry type Multi Polygon.
# Revisando cuales de los archivos son "gpkg" dentro de la carpeta 
list.files(pattern="gpkg")
## [1] "cauca_munic.gpkg" "municipos.gpkg"
# Cargamos estos datos exportados georeferenciados
colombia2 <- st_read("./municipos.gpkg")
## Reading layer `municipos' from data source 
##   `C:\Users\pc\OneDrive\Documentos\GB2\RSTUDIO\cuaderno3\municipos.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
# Filtramos el municipo y poligonos correspondientes 
cauca <- dplyr::filter(colombia2, dpto_cnmbr=="CAUCA")
Realizaremos un polteo rudimentario para observar la representacion de nuestros datos geoespaciales
# Utilizaremos la libreria plot
plot(st_geometry(cauca), col = sf.colors(12, categorical = TRUE), border = 'grey', 
     axes = TRUE)
plot(st_geometry(st_centroid(cauca)), pch = 3, col = 'red', add = TRUE)

Exportaremos los datos en formato GPKG para poder utilizar la libreria (dplyr) y realizar el analisis correspondiente para el departamento del cauca.
# Exportar solo para el departamento 
st_write(cauca, "cauca_munic.gpkg", driver = "GPKG", append = F)
## Deleting layer `cauca_munic' using driver `GPKG'
## Writing layer `cauca_munic' to data source `cauca_munic.gpkg' using driver `GPKG'
## Writing 42 features with 11 fields and geometry type Multi Polygon.
# Haremos mas directo el codigo sin utilizar PIPE pues los datos ya se encuentrar cargados en la data
  cities <- st_as_sf(cities_tabla, coords = c("lng", "lat"), crs = 4326)
Aqui confirmamos que nuestros datos se encuentrene en el mismo EPSG y y luego aplicaremos la funcion st_transform con el objetivo de dejar ambos datos en el mismo codigo de sistema de referencia.
st_crs(cauca)$epsg
## [1] 4326
st_crs(cities)$epsg
## [1] 4326
# filtrando solo para el departamento de interes este caso (cauca)
ncities <- st_transform(cities, crs = st_crs(cauca))
cities_cauca <-ncities[cauca, , op = st_within]

# Generando grafica y representando las principales ciudades del cauca
    plot(st_geometry(cauca), col = sf.colors(12, categorical = TRUE),border = 'grey', axes = TRUE) 
    plot(st_geometry(cities_cauca), pch = 20, col = "red", add = TRUE) 

Realizaremos ploteo para mejorar la distribucion de la informacion en el mapa.
# Aplicando una mejora al ploteo para que se vea mas entendible 
    ggplot() +
      #Add  municipalities
      geom_sf(data = cauca) +
      #Add cities layer
      geom_sf(data = cities_cauca, aes(color = city, label = city), size = 3) +
      #Add titles
      labs(x = "Longitud", y = "Latitud", title = "Ciudades del Cauca") +
      #Add theme
      theme_bw()

Mejoraremos algunos aspectos visuales de la composicion
ggplot() +
  # Capa base: Municipios del Cauca 
  geom_sf(data = cauca, fill = "gray", color = "gray30") +
  
  # Capa de ciudades
  geom_sf(data = cities_cauca, aes(color = city), size = 3) +
  
  # Elementos cartográficos: Escala y Flecha de Norte
  annotation_scale(location = "bl", width_hint = 0.3) +
  annotation_north_arrow(location = "tl", which_north = "true", 
                         style = north_arrow_fancy_orienteering) +
  
   # Textos: Títulos, ejes y autor
  labs(
    x = "Longitud", 
    y = "Latitud", 
    title = "Departamento del Cauca",
    caption = "Elaborado por: Thomas Espina | Fuente: DANE",
    color = "Ciudades" # Cambia el título de la leyenda
  ) +
  
    # Tema general y organización
  theme_bw() +
  theme(
    # Organizar la leyenda
    legend.position = "right", 
    legend.title = element_text(face = "bold"),
    
    legend.text = element_text(size = 7), 
    
    # Reducir el tamaño del símbolo (el puntico de color) en la leyenda
    legend.key.size = unit(0.4, "cm"),
    
    # Modificar la grilla (líneas punteadas sutiles)
    panel.grid.major = element_line(color = "gray80", linetype = "dashed"),
    
    # Centrar los títulos
    plot.title = element_text(face = "bold", hjust = 0.5)
  ) +
  
    # Dividir la leyenda en 2 columnas
  guides(color = guide_legend(ncol = 2))