Este cuaderno ilustra varias funcionalidades para obtener, procesar y visualizar modelos digitales de elevación (DEM) en R.En específico del departamento de Norte de Santander.
Los paquetes necesarios deben instalarse previamente desde la consola.
rm(list=ls())
library(elevatr)
## 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)
## Linking to GEOS 3.12.2, GDAL 3.9.3, PROJ 9.4.1; sf_use_s2() is TRUE
library(leaflet)
library(terra)
## terra 1.8.15
library(dplyr)
##
## Adjuntando el paquete: 'dplyr'
## The following objects are masked from 'package:terra':
##
## intersect, union
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
list.files("C:/Users/León Azul/Desktop/Trabajos Universidad Mateo/Geomática Básica 2024-2/Examen 2/Datos")
## [1] "Elevación_Nte_de_Santander.tif" "Elevacisn_Nte_de_Santander.tif"
## [3] "Municipios .gpkg" "Municipios .gpkg-shm"
## [5] "Municipios .gpkg-wal" "Municipios1.gpkg"
## [7] "NteSantander.gpkg"
munic <- sf::st_read("C:/Users/León Azul/Desktop/Trabajos Universidad Mateo/Geomática Básica 2024-2/Examen 2/Datos/Municipios1.gpkg")
## Reading layer `municipios___municipios_colombia' from data source
## `C:\Users\León Azul\Desktop\Trabajos Universidad Mateo\Geomática Básica 2024-2\Examen 2\Datos\Municipios1.gpkg'
## using driver `GPKG'
## Simple feature collection with 40 features and 4 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -73.63379 ymin: 6.872201 xmax: -72.04761 ymax: 9.290847
## Geodetic CRS: MAGNA-SIRGAS
(centers <- st_centroid(munic))
## Warning: st_centroid assumes attributes are constant over geometries
centers$x = st_coordinates(centers)[,1]
centers$y = st_coordinates(centers)[,2]
centers
(Nte_Santander = st_crs(st_geometry(munic)))
## Coordinate Reference System:
## User input: MAGNA-SIRGAS
## wkt:
## GEOGCRS["MAGNA-SIRGAS",
## DATUM["Marco Geocentrico Nacional de Referencia",
## ELLIPSOID["GRS 1980",6378137,298.257222101,
## LENGTHUNIT["metre",1]]],
## PRIMEM["Greenwich",0,
## ANGLEUNIT["degree",0.0174532925199433]],
## CS[ellipsoidal,2],
## AXIS["geodetic latitude (Lat)",north,
## ORDER[1],
## ANGLEUNIT["degree",0.0174532925199433]],
## AXIS["geodetic longitude (Lon)",east,
## ORDER[2],
## ANGLEUNIT["degree",0.0174532925199433]],
## USAGE[
## SCOPE["Horizontal component of 3D system."],
## AREA["Colombia - onshore and offshore. Includes San Andres y Providencia, Malpelo Islands, Roncador Bank, Serrana Bank and Serranilla Bank."],
## BBOX[-4.23,-84.77,15.51,-66.87]],
## ID["EPSG",4686]]
munic$area_m2 = sf::st_area(munic)
munic$area = munic$area_m2/1000000
munic$area = signif(munic$area, digits = 6)
munic
elevation <- get_elev_raster(munic, z = 10)
## Mosaicing & Projecting
## Note: Elevation units are in meters.
elevation
## class : RasterLayer
## dimensions : 4081, 3092, 12618452 (nrow, ncol, ncell)
## resolution : 0.0006822713, 0.0006822713 (x, y)
## extent : -73.82812, -71.71854, 6.664713, 9.449062 (xmin, xmax, ymin, ymax)
## crs : +proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs
## source : file293022f320ba.tif
## names : file293022f320ba
writeRaster(elevation, "C:/Users/León Azul/Desktop/Trabajos Universidad Mateo/Geomática Básica 2024-2/Examen 2/Datos/Elevación_Nte_de_Santander.tif", overwrite=TRUE)
(elevation2 <- terra::rast(elevation))
## class : SpatRaster
## dimensions : 4081, 3092, 1 (nrow, ncol, nlyr)
## resolution : 0.0006822713, 0.0006822713 (x, y)
## extent : -73.82812, -71.71854, 6.664713, 9.449062 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs
## source : file293022f320ba.tif
## name : file293022f320ba
pal <- colorNumeric(c("cyan", "forestgreen","yellow","tan","orange", "brown"), values(elevation),
na.color = "transparent")
(elevation3 <- terra::aggregate(elevation2, fact = 2))
## |---------|---------|---------|---------|=========================================
## class : SpatRaster
## dimensions : 2041, 1546, 1 (nrow, ncol, nlyr)
## resolution : 0.001364543, 0.001364543 (x, y)
## extent : -73.82812, -71.71854, 6.66403, 9.449062 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs
## source(s) : memory
## name : file293022f320ba
## min value : -391
## max value : 4737
elevation4 <- terra::crop(elevation3, munic, mask=TRUE)
library(terra)
library(tmap)
elevation_raster <- rast("C:/Users/León Azul/Desktop/Trabajos Universidad Mateo/Geomática Básica 2024-2/Examen 2/Datos/Elevación_Nte_de_Santander.tif")
tm_shape(elevation_raster) +
tm_raster(palette = terrain.colors(10), title = "Elevación (m)") +
tm_layout(legend.outside = TRUE)
##
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_tm_raster()`: migrate the argument(s) related to the scale of the
## visual variable `col` namely 'palette' (rename to 'values') to col.scale =
## tm_scale(<HERE>).
## [v3->v4] `tm_raster()`: migrate the argument(s) related to the legend of the
## visual variable `col` namely 'title' to 'col.legend = tm_legend(<HERE>)'
## SpatRaster object downsampled to 3633 by 2753 cells.
## 9. Leer datos de entrada
library(elevatr)
library(sf)
library(leaflet)
library(terra)
library(MultiscaleDTM)
library(exactextractr)
(dem = terra::rast("C:/Users/León Azul/Desktop/Trabajos Universidad Mateo/Geomática Básica 2024-2/Examen 2/Datos/Elevación_Nte_de_Santander.tif"))
## class : SpatRaster
## dimensions : 4081, 3092, 1 (nrow, ncol, nlyr)
## resolution : 0.0006822713, 0.0006822713 (x, y)
## extent : -73.82812, -71.71854, 6.664713, 9.449062 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=longlat +ellps=GRS80 +no_defs
## source : Elevación_Nte_de_Santander.tif
## name : Elevación_Nte_de_Santander
## min value : -1222
## max value : 4749
dem2 = terra::aggregate(dem,2, "mean")
## |---------|---------|---------|---------|=========================================
munic
st_crs(munic) # CRS del shapefile
## Coordinate Reference System:
## User input: MAGNA-SIRGAS
## wkt:
## GEOGCRS["MAGNA-SIRGAS",
## DATUM["Marco Geocentrico Nacional de Referencia",
## ELLIPSOID["GRS 1980",6378137,298.257222101,
## LENGTHUNIT["metre",1]]],
## PRIMEM["Greenwich",0,
## ANGLEUNIT["degree",0.0174532925199433]],
## CS[ellipsoidal,2],
## AXIS["geodetic latitude (Lat)",north,
## ORDER[1],
## ANGLEUNIT["degree",0.0174532925199433]],
## AXIS["geodetic longitude (Lon)",east,
## ORDER[2],
## ANGLEUNIT["degree",0.0174532925199433]],
## USAGE[
## SCOPE["Horizontal component of 3D system."],
## AREA["Colombia - onshore and offshore. Includes San Andres y Providencia, Malpelo Islands, Roncador Bank, Serrana Bank and Serranilla Bank."],
## BBOX[-4.23,-84.77,15.51,-66.87]],
## ID["EPSG",4686]]
crs(dem2) # CRS del raster
## [1] "GEOGCRS[\"unknown\",\n DATUM[\"Unknown based on GRS 1980 ellipsoid using towgs84=0,0,0,0,0,0,0\",\n ELLIPSOID[\"GRS 1980\",6378137,298.257222101004,\n LENGTHUNIT[\"metre\",1],\n ID[\"EPSG\",7019]]],\n PRIMEM[\"Greenwich\",0,\n ANGLEUNIT[\"degree\",0.0174532925199433,\n ID[\"EPSG\",9122]]],\n CS[ellipsoidal,2],\n AXIS[\"latitude\",north,\n ORDER[1],\n ANGLEUNIT[\"degree\",0.0174532925199433,\n ID[\"EPSG\",9122]]],\n AXIS[\"longitude\",east,\n ORDER[2],\n ANGLEUNIT[\"degree\",0.0174532925199433,\n ID[\"EPSG\",9122]]]]"
munic <- st_transform(munic, crs(dem2))
dem3 <- terra::crop(dem2, munic, mask = TRUE)
dem_plane <- project(dem3, "EPSG:9377")
(munic_plane = sf::st_transform(munic, "EPSG:9377"))
(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 : 1775, 1163, 2 (nrow, ncol, nlyr)
## resolution : 150.6407, 150.6407 (x, y)
## extent : 4929942, 5105137, 2317391, 2584779 (xmin, xmax, ymin, ymax)
## coord. ref. : MAGNA-SIRGAS 2018 / Origen-Nacional (EPSG:9377)
## source(s) : memory
## names : slope, aspect
## min values : 0.003311737, 0.0000
## max values : 75.537534350, 359.9999
(slope = subset(slp_asp, 1))
## class : SpatRaster
## dimensions : 1775, 1163, 1 (nrow, ncol, nlyr)
## resolution : 150.6407, 150.6407 (x, y)
## extent : 4929942, 5105137, 2317391, 2584779 (xmin, xmax, ymin, ymax)
## coord. ref. : MAGNA-SIRGAS 2018 / Origen-Nacional (EPSG:9377)
## source(s) : memory
## name : slope
## min value : 0.003311737
## max value : 75.537534350
terra::hist(slope,
main = "Nte_Santander's slope",
xlab = "Slope (in degrees)")
(aspect =subset(slp_asp, 2))
## class : SpatRaster
## dimensions : 1775, 1163, 1 (nrow, ncol, nlyr)
## resolution : 150.6407, 150.6407 (x, y)
## extent : 4929942, 5105137, 2317391, 2584779 (xmin, xmax, ymin, ymax)
## coord. ref. : MAGNA-SIRGAS 2018 / Origen-Nacional (EPSG:9377)
## source(s) : memory
## name : aspect
## min value : 0.0000
## max value : 359.9999
terra::hist(aspect,
main = "Nte_Santander's aspect",
xlab = "Aspect (in degrees)")
(slope_perc = tan(slope*(pi/180))*100)
## class : SpatRaster
## dimensions : 1775, 1163, 1 (nrow, ncol, nlyr)
## resolution : 150.6407, 150.6407 (x, y)
## extent : 4929942, 5105137, 2317391, 2584779 (xmin, xmax, ymin, ymax)
## coord. ref. : MAGNA-SIRGAS 2018 / Origen-Nacional (EPSG:9377)
## source(s) : memory
## name : slope
## min value : 5.780071e-03
## max value : 3.877189e+02
terra::hist(slope_perc,
main = "Nte_Santander's slope",
xlab = "Slope (in percentage)")
terra::hist(slope_perc)
## 12. Calcular estadísticas zonales:
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)
(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% | |===== | 8% | |======= | 10% | |========= | 12% | |========== | 15% | |============ | 18% | |============== | 20% | |================ | 22% | |================== | 25% | |=================== | 28% | |===================== | 30% | |======================= | 32% | |======================== | 35% | |========================== | 38% | |============================ | 40% | |============================== | 42% | |================================ | 45% | |================================= | 48% | |=================================== | 50% | |===================================== | 52% | |====================================== | 55% | |======================================== | 58% | |========================================== | 60% | |============================================ | 62% | |============================================== | 65% | |=============================================== | 68% | |================================================= | 70% | |=================================================== | 72% | |==================================================== | 75% | |====================================================== | 78% | |======================================================== | 80% | |========================================================== | 82% | |============================================================ | 85% | |============================================================= | 88% | |=============================================================== | 90% | |================================================================= | 92% | |================================================================== | 95% | |==================================================================== | 98% | |======================================================================| 100%
## [1] 8.6702213 26.9235306 44.9074860 34.2686043 43.6437950 35.0278358
## [7] 35.4857483 30.9476299 41.6343918 28.3918533 41.6895752 27.8760204
## [13] 32.0564842 21.0131588 18.4156361 34.5212708 34.9811592 29.1976566
## [19] 37.4988747 15.7919779 26.5164795 19.6292419 37.1167183 33.4874992
## [25] 28.8898964 34.7548332 37.1878052 0.6774865 31.2936707 39.9569283
## [31] 33.4410667 15.2708139 26.6202831 25.2895069 29.5764160 31.8660564
## [37] 8.1980619 36.7857590 39.5793037 18.2338161
hist(munic$mean_slope,
main = "Nte_Santander's mean slope",
xlab = "Slope (in percentage)")
(munic$class <- exactextractr::exact_extract(rc, munic, 'mode'))
## Warning in .local(x, y, ...): Polygons transformed to raster CRS (EPSG:9377)
## | | | 0% | |== | 2% | |==== | 5% | |===== | 8% | |======= | 10% | |========= | 12% | |========== | 15% | |============ | 18% | |============== | 20% | |================ | 22% | |================== | 25% | |=================== | 28% | |===================== | 30% | |======================= | 32% | |======================== | 35% | |========================== | 38% | |============================ | 40% | |============================== | 42% | |================================ | 45% | |================================= | 48% | |=================================== | 50% | |===================================== | 52% | |====================================== | 55% | |======================================== | 58% | |========================================== | 60% | |============================================ | 62% | |============================================== | 65% | |=============================================== | 68% | |================================================= | 70% | |=================================================== | 72% | |==================================================== | 75% | |====================================================== | 78% | |======================================================== | 80% | |========================================================== | 82% | |============================================================ | 85% | |============================================================= | 88% | |=============================================================== | 90% | |================================================================= | 92% | |================================================================== | 95% | |==================================================================== | 98% | |======================================================================| 100%
## [1] 1 5 5 5 5 5 5 5 5 5 5 5 5 4 4 5 5 5 5 1 5 4 5 5 5 5 5 1 5 5 5 4 4 4 5 5 1 5
## [39] 5 5
hist(munic$class,
main = "Nte_Santander's reclassified slope",
xlab = "Slope (as a category)")
### 12.1 Transformemos la pendiente nuevamente a coordenadas
geográficas:
(rc.geo = project(rc, "EPSG:4326"))
## class : SpatRaster
## dimensions : 1774, 1169, 1 (nrow, ncol, nlyr)
## resolution : 0.001364545, 0.001364545 (x, y)
## extent : -73.63815, -72.043, 6.871343, 9.292045 (xmin, xmax, ymin, ymax)
## coord. ref. : lon/lat WGS 84 (EPSG:4326)
## source(s) : memory
## name : slope
## min value : 1.0000
## max value : 366.9063
(slope.geo = project(slope_perc, "EPSG:4326"))
## class : SpatRaster
## dimensions : 1774, 1169, 1 (nrow, ncol, nlyr)
## resolution : 0.001364545, 0.001364545 (x, y)
## extent : -73.63815, -72.043, 6.871343, 9.292045 (xmin, xmax, ymin, ymax)
## coord. ref. : lon/lat WGS 84 (EPSG:4326)
## source(s) : memory
## name : slope
## min value : 0.03222043
## max value : 366.90628052
palredgreen <- colorNumeric(c("darkseagreen3","yellow2", "orange", "brown2", "darkred"), values(slope.geo),
na.color = "transparent")
leaflet(munic) %>% addTiles() %>% setView(-72.36, 6.99, 9.30) %>%
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 Cordoba (%)")
library(leaflet)
# Crear paleta de colores para la pendiente
palredgreen <- colorNumeric(
palette = c("darkseagreen3", "yellow2", "orange", "brown2", "darkred"),
domain = values(slope.geo),
na.color = "transparent"
)
# Crear mapa interactivo con Leaflet
leaflet(munic) %>%
addTiles() %>%
setView(-72.36, 6.99, zoom = 9.30) %>%
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>",
"Mean slope: ", round(munic$mean_slope, 2), "%"
)
) %>%
addRasterImage(slope.geo, colors = palredgreen, opacity = 0.8) %>%
addLegend(
pal = palredgreen, values = values(slope.geo),
title = "Terrain slope in degrees"
) %>%
addLabelOnlyMarkers(
data = munic,
lng = centers$x, lat = centers$y,
label = ~paste(mpio_cnmbr, "(", round(mean_slope, 2), "°)"),
labelOptions = labelOptions(
noHide = TRUE, direction = "top",
textOnly = TRUE, style = list("font-weight" = "bold")
)
)
munic$mean_aspect <- exactextractr::exact_extract(aspect, munic, 'mean')
## Warning in .local(x, y, ...): Polygons transformed to raster CRS (EPSG:9377)
## | | | 0% | |== | 2% | |==== | 5% | |===== | 8% | |======= | 10% | |========= | 12% | |========== | 15% | |============ | 18% | |============== | 20% | |================ | 22% | |================== | 25% | |=================== | 28% | |===================== | 30% | |======================= | 32% | |======================== | 35% | |========================== | 38% | |============================ | 40% | |============================== | 42% | |================================ | 45% | |================================= | 48% | |=================================== | 50% | |===================================== | 52% | |====================================== | 55% | |======================================== | 58% | |========================================== | 60% | |============================================ | 62% | |============================================== | 65% | |=============================================== | 68% | |================================================= | 70% | |=================================================== | 72% | |==================================================== | 75% | |====================================================== | 78% | |======================================================== | 80% | |========================================================== | 82% | |============================================================ | 85% | |============================================================= | 88% | |=============================================================== | 90% | |================================================================= | 92% | |================================================================== | 95% | |==================================================================== | 98% | |======================================================================| 100%
library(leaflet)
# Definir la paleta de colores para el aspecto (orientación del terreno)
pal_aspect <- colorNumeric(
palette = c("red", "orange", "yellow", "green", "cyan", "blue", "magenta", "purple"),
domain = values(aspect),
na.color = "transparent"
)
# Crear el mapa con Leaflet
leaflet(munic) %>%
addTiles() %>%
setView(-72.36, 6.99, zoom = 9.30) %>%
addPolygons(
color = "gray", weight = 1.0, smoothFactor = 0.5,
opacity = 0.4, fillOpacity = 0.10,
popup = paste(
"Municipio: ", munic$mpio_cnmbr, "<br>",
"Aspect (°): ", round(munic$mean_aspect, 2)
)
) %>%
addRasterImage(aspect, colors = pal_aspect, opacity = 0.8) %>%
addLegend(
pal = pal_aspect, values = values(aspect),
title = "Aspect (°)"
)