Primero para poder empezar realizamos Limpieza del cuaderno
rm(list=ls())
Descargamos la libreria que vamos a usar para el presente proyecto
warning=FALSE
library(elevatr)
## Warning: package 'elevatr' was built under R version 4.3.3
## elevatr v0.99.0 NOTE: Version 0.99.0 of 'elevatr' uses 'sf' and 'terra'. Use
## of the 'sp', 'raster', and underlying 'rgdal' packages by 'elevatr' is being
## deprecated; however, get_elev_raster continues to return a RasterLayer. This
## will be dropped in future versions, so please plan accordingly.
library(sf)
## Warning: package 'sf' was built under R version 4.3.3
## Linking to GEOS 3.11.2, GDAL 3.8.2, PROJ 9.3.1; sf_use_s2() is TRUE
library(leaflet)
## Warning: package 'leaflet' was built under R version 4.3.3
library(terra)
## Warning: package 'terra' was built under R version 4.3.3
## terra 1.8.15
library(MultiscaleDTM)
## Warning: package 'MultiscaleDTM' was built under R version 4.3.3
library(exactextractr)
## Warning: package 'exactextractr' was built under R version 4.3.3
Llamamos los datos del proyecto anterior
(dem = terra::rast("elev_Valledc_z10.tif"))
## class : SpatRaster
## dimensions : 3580, 3077, 1 (nrow, ncol, nlyr)
## resolution : 0.0006856326, 0.0006856326 (x, y)
## extent : -77.69531, -75.58562, 2.811443, 5.266008 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +ellps=GRS80 +no_defs
## source : elev_Valledc_z10.tif
## name : elev_Valledc_z10
## min value : -2050
## max value : 5373
Reducimos para evitar llenar la memoria
dem2 = terra::aggregate(dem,2, "mean")
## |---------|---------|---------|---------|=========================================
Leemos el Municipio en extension .gpkg
(munic <- sf::st_read("mun_Valle.gpkg"))
## Reading layer `municipios_colombia' from data source
## `C:\Users\lacj7\OneDrive\Escritorio\GB2\PROYECTO_4\datos\mun_Valle.gpkg'
## using driver `GPKG'
## Simple feature collection with 42 features and 5 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -77.54977 ymin: 3.091239 xmax: -75.70724 ymax: 5.047394
## Geodetic CRS: MAGNA-SIRGAS
## Simple feature collection with 42 features and 5 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -77.54977 ymin: 3.091239 xmax: -75.70724 ymax: 5.047394
## Geodetic CRS: MAGNA-SIRGAS
## First 10 features:
## dpto_ccdgo mpio_ccdgo mpio_cdpmp mpio_cnmbr Area_Km2
## 1 76 001 76001 CALI 561.96643
## 2 76 020 76020 ALCALÁ 62.30168
## 3 76 036 76036 ANDALUCÍA 110.31362
## 4 76 041 76041 ANSERMANUEVO 305.09706
## 5 76 054 76054 ARGELIA 90.67825
## 6 76 100 76100 BOLÍVAR 742.38434
## 7 76 109 76109 BUENAVENTURA 6274.60975
## 8 76 111 76111 GUADALAJARA DE BUGA 824.83594
## 9 76 113 76113 BUGALAGRANDE 396.29099
## 10 76 122 76122 CAICEDONIA 166.82613
## geom
## 1 MULTIPOLYGON (((-76.59175 3...
## 2 MULTIPOLYGON (((-75.83262 4...
## 3 MULTIPOLYGON (((-76.22406 4...
## 4 MULTIPOLYGON (((-76.01558 4...
## 5 MULTIPOLYGON (((-76.14316 4...
## 6 MULTIPOLYGON (((-76.27584 4...
## 7 MULTIPOLYGON (((-77.2381 4....
## 8 MULTIPOLYGON (((-76.31608 3...
## 9 MULTIPOLYGON (((-76.15131 4...
## 10 MULTIPOLYGON (((-75.8539 4....
dem3 = terra::crop(dem2,munic, mask=TRUE)
## Warning: [crop] CRS do not match
Cambiamos a las coordenadas de Colombia
(dem_plane = project(dem3, "EPSG:9377"))
## class : SpatRaster
## dimensions : 1430, 1353, 1 (nrow, ncol, nlyr)
## resolution : 152.1184, 152.1184 (x, y)
## extent : 4494105, 4699921, 1900030, 2117560 (xmin, xmax, ymin, ymax)
## coord. ref. : MAGNA-SIRGAS 2018 / Origen-Nacional (EPSG:9377)
## source(s) : memory
## name : elev_Valledc_z10
## min value : -252.9045
## max value : 4201.2246
Cambiamos para el vector
(munic_plane = sf::st_transform(munic, "EPSG:9377"))
## Simple feature collection with 42 features and 5 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: 4494194 ymin: 1900273 xmax: 4699750 ymax: 2116536
## Projected CRS: MAGNA-SIRGAS 2018 / Origen-Nacional
## First 10 features:
## dpto_ccdgo mpio_ccdgo mpio_cdpmp mpio_cnmbr Area_Km2
## 1 76 001 76001 CALI 561.96643
## 2 76 020 76020 ALCALÁ 62.30168
## 3 76 036 76036 ANDALUCÍA 110.31362
## 4 76 041 76041 ANSERMANUEVO 305.09706
## 5 76 054 76054 ARGELIA 90.67825
## 6 76 100 76100 BOLÍVAR 742.38434
## 7 76 109 76109 BUENAVENTURA 6274.60975
## 8 76 111 76111 GUADALAJARA DE BUGA 824.83594
## 9 76 113 76113 BUGALAGRANDE 396.29099
## 10 76 122 76122 CAICEDONIA 166.82613
## geom
## 1 MULTIPOLYGON (((4600987 195...
## 2 MULTIPOLYGON (((4685860 208...
## 3 MULTIPOLYGON (((4642160 202...
## 4 MULTIPOLYGON (((4665634 209...
## 5 MULTIPOLYGON (((4651417 208...
## 6 MULTIPOLYGON (((4636542 205...
## 7 MULTIPOLYGON (((4529330 200...
## 8 MULTIPOLYGON (((4631835 199...
## 9 MULTIPOLYGON (((4650286 203...
## 10 MULTIPOLYGON (((4683364 204...
llamamos la funcion SlpAsp
(slp_asp = MultiscaleDTM::SlpAsp(
dem_plane,
w = c(3, 3),
unit = "degrees",
method = "queen",
metrics = c("slope", "aspect"),
na.rm = TRUE,
include_scale = FALSE,
mask_aspect = TRUE
))
## class : SpatRaster
## dimensions : 1430, 1353, 2 (nrow, ncol, nlyr)
## resolution : 152.1184, 152.1184 (x, y)
## extent : 4494105, 4699921, 1900030, 2117560 (xmin, xmax, ymin, ymax)
## coord. ref. : MAGNA-SIRGAS 2018 / Origen-Nacional (EPSG:9377)
## source(s) : memory
## names : slope, aspect
## min values : 0.00000, 1.119667e-04
## max values : 74.02856, 3.599985e+02
Lo dividimos en dos partes
Capa 1:
(slope = subset(slp_asp, 1))
## class : SpatRaster
## dimensions : 1430, 1353, 1 (nrow, ncol, nlyr)
## resolution : 152.1184, 152.1184 (x, y)
## extent : 4494105, 4699921, 1900030, 2117560 (xmin, xmax, ymin, ymax)
## coord. ref. : MAGNA-SIRGAS 2018 / Origen-Nacional (EPSG:9377)
## source(s) : memory
## name : slope
## min value : 0.00000
## max value : 74.02856
Valores
terra::hist(slope,
main = "Pendiente del Valle del cauca",
xlab = "Pendiente (en grados)")
## Warning: [hist] a sample of 52% of the cells was used (of which 54% was NA)
Capa 2:
(aspect =subset(slp_asp, 2))
## class : SpatRaster
## dimensions : 1430, 1353, 1 (nrow, ncol, nlyr)
## resolution : 152.1184, 152.1184 (x, y)
## extent : 4494105, 4699921, 1900030, 2117560 (xmin, xmax, ymin, ymax)
## coord. ref. : MAGNA-SIRGAS 2018 / Origen-Nacional (EPSG:9377)
## source(s) : memory
## name : aspect
## min value : 1.119667e-04
## max value : 3.599985e+02
Valores
terra::hist(aspect,
main = "Orientacion del Valle",
xlab = "Orientacion (en grados)")
## Warning: [hist] a sample of 52% of the cells was used (of which 54% was NA)
Ahora hallamos la pendiente en porcentaje para poder clasificar las zonas
(slope_perc = tan(slope*(pi/180))*100)
## class : SpatRaster
## dimensions : 1430, 1353, 1 (nrow, ncol, nlyr)
## resolution : 152.1184, 152.1184 (x, y)
## extent : 4494105, 4699921, 1900030, 2117560 (xmin, xmax, ymin, ymax)
## coord. ref. : MAGNA-SIRGAS 2018 / Origen-Nacional (EPSG:9377)
## source(s) : memory
## name : slope
## min value : 0.0000
## max value : 349.3986
Valores
terra::hist(slope_perc,
main = "Pendiente del valle del cauca",
xlab = "Pendiente (en porcentage)")
## Warning: [hist] a sample of 52% of the cells was used (of which 54% was NA)
m <- c(0, 3, 1,
3, 7, 2,
7, 12, 3,
12, 25, 4,
25, 50, 5,
50, 75, 6,
75, 160, 7)
m <- matrix(m, ncol=3, byrow = TRUE)
rc <- classify(slope_perc, m, right=TRUE)
warning=FALSE
(munic$mean_slope <- exactextractr::exact_extract(slope_perc, munic, 'mean'))
## Warning in .local(x, y, ...): Polygons transformed to raster CRS (EPSG:9377)
## | | | 0% | |== | 2% | |=== | 5% | |===== | 7% | |======= | 10% | |======== | 12% | |========== | 14% | |============ | 17% | |============= | 19% | |=============== | 21% | |================= | 24% | |================== | 26% | |==================== | 29% | |====================== | 31% | |======================= | 33% | |========================= | 36% | |=========================== | 38% | |============================ | 40% | |============================== | 43% | |================================ | 45% | |================================= | 48% | |=================================== | 50% | |===================================== | 52% | |====================================== | 55% | |======================================== | 57% | |========================================== | 60% | |=========================================== | 62% | |============================================= | 64% | |=============================================== | 67% | |================================================ | 69% | |================================================== | 71% | |==================================================== | 74% | |===================================================== | 76% | |======================================================= | 79% | |========================================================= | 81% | |========================================================== | 83% | |============================================================ | 86% | |============================================================== | 88% | |=============================================================== | 90% | |================================================================= | 93% | |=================================================================== | 95% | |==================================================================== | 98% | |======================================================================| 100%
## [1] 19.1932716 7.0536819 6.5234451 24.4195595 29.2239342 33.5480080
## [7] 14.4227972 29.3312092 10.4425707 19.4222984 29.9164867 0.5738842
## [13] 8.4911633 30.0080242 39.9681816 34.8505516 21.2526875 32.7035942
## [19] 30.7923889 27.2616692 10.1506596 19.0136471 19.5517540 14.8743944
## [25] 9.2575541 10.9017820 19.2761707 26.3611240 15.6934271 23.0123882
## [31] 16.8672638 15.2212105 24.7992954 20.7394142 26.5074520 26.5728569
## [37] 7.9285340 31.6442127 18.7146034 17.6516132 19.1481228 5.5441055
hist(munic$mean_slope,
main = "Pendiente media Valle del cauca",
xlab = "Pendiente (en porcentaje)",
breaks = 10, # Ajusta el número de barras del histograma
xlim = c(0, 60), # Ajusta el rango del eje X según tus datos
col = "lightblue")
(munic$class <- exactextractr::exact_extract(rc, munic, 'mode'))
## Warning in .local(x, y, ...): Polygons transformed to raster CRS (EPSG:9377)
## | | | 0% | |== | 2% | |=== | 5% | |===== | 7% | |======= | 10% | |======== | 12% | |========== | 14% | |============ | 17% | |============= | 19% | |=============== | 21% | |================= | 24% | |================== | 26% | |==================== | 29% | |====================== | 31% | |======================= | 33% | |========================= | 36% | |=========================== | 38% | |============================ | 40% | |============================== | 43% | |================================ | 45% | |================================= | 48% | |=================================== | 50% | |===================================== | 52% | |====================================== | 55% | |======================================== | 57% | |========================================== | 60% | |=========================================== | 62% | |============================================= | 64% | |=============================================== | 67% | |================================================ | 69% | |================================================== | 71% | |==================================================== | 74% | |===================================================== | 76% | |======================================================= | 79% | |========================================================= | 81% | |========================================================== | 83% | |============================================================ | 86% | |============================================================== | 88% | |=============================================================== | 90% | |================================================================= | 93% | |=================================================================== | 95% | |==================================================================== | 98% | |======================================================================| 100%
## [1] 1 2 1 5 5 5 1 5 1 5 5 1 1 5 5 5 1 5 5 5 1 1 4 1 1 1 1 1 4 5 5 1 5 5 5 5 2 5
## [39] 4 4 5 1
hist(munic$class,
main = "Pendiente reclasificada del Valle del Cauca",
xlab = "Pendiente (Como categoria)",
breaks = 10,
xlim = c(0, 10),
col = "lightblue")
(rc.geo = project(rc, "EPSG:4326"))
## class : SpatRaster
## dimensions : 1439, 1357, 1 (nrow, ncol, nlyr)
## resolution : 0.001371234, 0.001371234 (x, y)
## extent : -77.56098, -75.70021, 3.085094, 5.058299 (xmin, xmax, ymin, ymax)
## coord. ref. : lon/lat WGS 84 (EPSG:4326)
## source(s) : memory
## name : slope
## min value : 0.000
## max value : 292.879
(slope.geo = project(slope_perc, "EPSG:4326"))
## class : SpatRaster
## dimensions : 1439, 1357, 1 (nrow, ncol, nlyr)
## resolution : 0.001371234, 0.001371234 (x, y)
## extent : -77.56098, -75.70021, 3.085094, 5.058299 (xmin, xmax, ymin, ymax)
## coord. ref. : lon/lat WGS 84 (EPSG:4326)
## source(s) : memory
## name : slope
## min value : 0.0000
## max value : 297.0677
palredgreen <- colorNumeric(c("darkseagreen3","yellow2", "orange", "brown2", "darkred"), values(slope.geo),
na.color = "transparent")
leaflet(munic) %>%
addTiles() %>%
setView(-76.5, 3.5, 7) %>% # Coordenadas del Valle del Cauca con un zoom más amplio
addPolygons(color = "gray", weight = 1.0, smoothFactor = 0.5,
opacity = 0.4, fillOpacity = 0.10,
popup = paste("Municipio: ", munic$mpio_cnmbr, "<br>",
"Slope class: ", munic$class, "<br>")) %>%
addRasterImage(slope.geo, colors = palredgreen, opacity = 0.8) %>%
addLegend(pal = palredgreen, values = values(slope.geo),
title = "Terrain slope in Valle del Cauca (%)")
## Warning: sf layer has inconsistent datum (+proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs).
## Need '+proj=longlat +datum=WGS84'
munic$longitude <- st_coordinates(st_centroid(munic))[,1]
## Warning: st_centroid assumes attributes are constant over geometries
munic$latitude <- st_coordinates(st_centroid(munic))[,2]
## Warning: st_centroid assumes attributes are constant over geometries
# Convertir la pendiente de porcentaje a grados
slope_deg <- atan(slope*(pi/180)) * (180/pi)
# Calcular la pendiente promedio en grados por municipio
munic$mean_slope_deg <- exactextractr::exact_extract(slope_deg, munic, 'mean')
## Warning in .local(x, y, ...): Polygons transformed to raster CRS (EPSG:9377)
## | | | 0% | |== | 2% | |=== | 5% | |===== | 7% | |======= | 10% | |======== | 12% | |========== | 14% | |============ | 17% | |============= | 19% | |=============== | 21% | |================= | 24% | |================== | 26% | |==================== | 29% | |====================== | 31% | |======================= | 33% | |========================= | 36% | |=========================== | 38% | |============================ | 40% | |============================== | 43% | |================================ | 45% | |================================= | 48% | |=================================== | 50% | |===================================== | 52% | |====================================== | 55% | |======================================== | 57% | |========================================== | 60% | |=========================================== | 62% | |============================================= | 64% | |=============================================== | 67% | |================================================ | 69% | |================================================== | 71% | |==================================================== | 74% | |===================================================== | 76% | |======================================================= | 79% | |========================================================= | 81% | |========================================================== | 83% | |============================================================ | 86% | |============================================================== | 88% | |=============================================================== | 90% | |================================================================= | 93% | |=================================================================== | 95% | |==================================================================== | 98% | |======================================================================| 100%
# Crear el mapa
leaflet(munic) %>%
addTiles() %>%
setView(-76.5, 3.5, 7) %>% # Coordenadas del Valle del Cauca, las mismas de antes
addPolygons(color = "gray", weight = 1.0, smoothFactor = 0.5,
opacity = 0.4, fillOpacity = 0.10,
popup = paste("Municipio: ", munic$mpio_cnmbr, "<br>",
"clase de Pendiente: ", munic$class, "<br>",
"pendiente promedio: ", round(munic$mean_slope_deg, 1), "°", "<br>")) %>%
addRasterImage(slope.geo, colors = palredgreen, opacity = 0.8) %>%
addLegend(pal = palredgreen, values = values(slope.geo),
title = "Pendiente del terreno Valle del Cauca (%)") %>%
addLabelOnlyMarkers(
lng = munic$longitude, # Coordenadas de los municipios
lat = munic$latitude, # Coordenadas de los municipios
label = paste(munic$mpio_cnmbr, ": ", round(munic$mean_slope_deg, 1), "°", sep = ""),
labelOptions = labelOptions(noHide = TRUE, direction = "auto", textsize = "12px")
)
## Warning: sf layer has inconsistent datum (+proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs).
## Need '+proj=longlat +datum=WGS84'
# Crear la paleta de colores para el aspecto
pal_aspect <- colorNumeric(
palette = c("blue", "green", "yellow", "orange", "red", "pink", "purple", "lightblue"),
domain = values(aspect),
na.color = "transparent"
)
# Crear el mapa con leaflet
leaflet(munic) %>%
addTiles() %>%
setView(-76.5, 3.5, 7) %>% # Coordenadas del Valle del Cauca
addPolygons(color = "gray", weight = 1.0, smoothFactor = 0.5,
opacity = 0.4, fillOpacity = 0.10,
popup = paste("Municipio: ", munic$mpio_cnmbr, "<br>",
"Clase de Pendiente: ", munic$class, "<br>")) %>%
addRasterImage(aspect, colors = pal_aspect, opacity = 0.8) %>%
addLegend(pal = pal_aspect, values = values(aspect),
title = "Direccion terreno basado en DTM (Grados)", opacity = 0.7) %>%
addControl(
html = "<div style='background-color: white; padding: 10px; border-radius: 5px; border: 2px solid black; opacity: 0.8; font-size: 14px;'>
<b>Direction Legend</b><br>
<span style='color: blue;'>Norte</span><br>
<span style='color: green;'>Noreste</span><br>
<span style='color: yellow;'>Este</span><br>
<span style='color: orange;'>Sureste</span><br>
<span style='color: red;'>Sur</span><br>
<span style='color: pink;'>Suroeste</span><br>
<span style='color: purple;'>Oeste</span><br>
<span style='color: lightblue;'>Noroeste</span><br>
</div>",
position = "bottomright",
className = "leaflet-control-legend"
)
## Warning: sf layer has inconsistent datum (+proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs).
## Need '+proj=longlat +datum=WGS84'
Principalmente se uso Lizarazo, I., 2025. Geomorphometric terrain attributes in R. Available at https://rpubs.com/ials2un/geomorphometric
sessionInfo()
## R version 4.3.1 (2023-06-16 ucrt)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 11 x64 (build 22631)
##
## Matrix products: default
##
##
## locale:
## [1] LC_COLLATE=Spanish_Spain.utf8 LC_CTYPE=Spanish_Spain.utf8
## [3] LC_MONETARY=Spanish_Spain.utf8 LC_NUMERIC=C
## [5] LC_TIME=Spanish_Spain.utf8
##
## time zone: America/Bogota
## tzcode source: internal
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] exactextractr_0.10.0 MultiscaleDTM_0.9.1 terra_1.8-15
## [4] leaflet_2.2.2 sf_1.0-19 elevatr_0.99.0
##
## loaded via a namespace (and not attached):
## [1] s2_1.1.7 sass_0.4.9 generics_0.1.3 class_7.3-22
## [5] KernSmooth_2.23-21 lattice_0.21-8 digest_0.6.37 magrittr_2.0.3
## [9] rgl_1.3.17 evaluate_1.0.1 grid_4.3.1 fastmap_1.2.0
## [13] jsonlite_1.8.9 e1071_1.7-16 DBI_1.2.3 promises_1.3.2
## [17] purrr_1.0.2 scales_1.3.0 crosstalk_1.2.1 codetools_0.2-19
## [21] jquerylib_0.1.4 cli_3.6.3 shiny_1.10.0 rlang_1.1.4
## [25] units_0.8-5 munsell_0.5.1 base64enc_0.1-3 cachem_1.1.0
## [29] yaml_2.3.10 raster_3.6-31 tools_4.3.1 dplyr_1.1.4
## [33] colorspace_2.1-1 httpuv_1.6.15 png_0.1-8 vctrs_0.6.5
## [37] R6_2.5.1 mime_0.12 proxy_0.4-27 lifecycle_1.0.4
## [41] classInt_0.4-11 htmlwidgets_1.6.4 pkgconfig_2.0.3 progressr_0.15.1
## [45] bslib_0.8.0 pillar_1.10.0 later_1.4.1 glue_1.8.0
## [49] Rcpp_1.0.13-1 tidyselect_1.2.1 xfun_0.49 tibble_3.2.1
## [53] rstudioapi_0.17.1 knitr_1.49 farver_2.1.2 xtable_1.8-4
## [57] htmltools_0.5.8.1 rmarkdown_2.29 wk_0.9.4 compiler_4.3.1
## [61] sp_2.1-4