1. Introducción

Este es el segundo cuaderno R Markdown para el curso Geomatica Básica 2022. Ilustra cómo hacer mapas temáticos que muestren la participación municipal de los dos grupos de cultivos más importantes para un departamento determinado. Usaremos como fuente principal los archivos csv guardados en el cuaderno EVA, así como un shapefile de municipios obtenidos en clase.

2. Configuración

En este paso, instalaremos y cargaremos las bibliotecas R necesarias.

#run the following lines from the command line:
#install.packages('dplyr')
#install.packages('readxl')
#install.packages('sf)
library(sf)
## Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(readr)

3. Leer archivos relacionados con municipios, cultivos y ciudades

Trabajaré con el Departamento de Tolima.

Antes de comenzar, asegúrese de haber guardado los siguientes archivos en su computadora:

-Un archivo de forma con los municipios de su departamento (como se produjo en clase) -Un archivo csv con estadísticas de EVA 2020 para el grupo de cultivos seleccionado (como se produjo en el primer cuaderno) Además, se necesitara un archivo con ciudades de Colombia. Puede descargarlo desde https://simplemaps.com/data/co-cities. Luego, mueva el archivo co.csv descargado a su directorio de trabajo.

-Ahora, procedamos a leer los archivos basados en EVA obtenidos del primer cuaderno:

library(readxl)
cereales <- read_excel("EVA_19_22.xlsx")
View(cereales)
alg_tol=cereales%>%group_by(COD_MUN, MUNICIPIO, GRUPO)%>%filter(DEPTO=="Tolima"& GRUPO=="Cereales")%>% 
  summarize(max_prod = max(PRODUCCION, na.rm = TRUE)) %>%
  arrange(desc(max_prod))
## `summarise()` has grouped output by 'COD_MUN', 'MUNICIPIO'. You can override
## using the `.groups` argument.
write_csv(alg_tol,"Tolima_Algodon.csv")
library(sf)
# this shapefile must have a 4326 EPSG code
# this shapefile was obtained in class using QGIS
(mun.tmp =  st_read("C:/Users/camil/OneDrive/Escritorio/Geomatica/CuadernoEVA/MGN_MPIO_POLITICO.shp"))
## Reading layer `MGN_MPIO_POLITICO' from data source 
##   `C:\Users\camil\OneDrive\Escritorio\Geomatica\CuadernoEVA\MGN_MPIO_POLITICO.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

-Seleccionemos algunos atributos para limpiar el objeto:

# check the objet output in the last chunk and
# change attribute names according to your own data
mun.tmp %>% filter(DPTO_CNMBR=="TOLIMA") %>% select(MPIO_CCDGO, MPIO_CNMBR, MPIO_NAREA) -> municipios
municipios
st_transform(x = municipios,crs = 4326)

-Ahora, lea el archivo csv de las ciudades:

ciudadesco=read.csv("ciudadesco.csv")
ciudadesco

Tenga en cuenta que hay 1102 filas que representan ciudades en Colombia. Tenga en cuenta que el objeto de ciudades es un objeto no espacial (un tibble, en realidad).

Tenga en cuenta también que los valores de las coordenadas se almacenan en los atributos “lng” (latitud) y “lat” (longitud).

Para convertir ciudades en un objeto espacial (un objeto de característica simple, en este caso):

# Convert data frame to simple feature object
sf.cities <-  st_as_sf(x = ciudadesco, 
                        coords = c("lng", "lat"))
sf.cities

¡Tenga en cuenta el CRS que falta!

Agreguemos el CRS usando el código EPSG:

st_crs(sf.cities) <- 4326
st_crs(municipios)=4326
## Warning: st_crs<- : replacing crs does not reproject data; use st_transform for
## that

4. Subconjunto de datos relevantes para nuestro departamento

Como estamos interesados en un solo departamento, necesitamos crear una unión espacial:

# find points (cities) within polygons (our municipalities)
sf.cities.joined <- st_join(sf.cities, municipios, join = st_intersects)
tol.cities=filter(sf.cities.joined,admin_name=="Tolima")
library(tmap)
## The legacy packages maptools, rgdal, and rgeos, underpinning the sp package,
## which was just loaded, were retired in October 2023.
## Please refer to R-spatial evolution reports for details, especially
## https://r-spatial.org/r/2023/05/15/evolution4.html.
## It may be desirable to make the sf package available;
## package maintainers should consider adding sf to Suggests:.
## Breaking News: tmap 3.x is retiring. Please test v4, e.g. with
## remotes::install_github('r-tmap/tmap')
library(classInt)
library(ggrepel)
## Loading required package: ggplot2
class(alg_tol$COD_MUN)
## [1] "character"
class(mun.tmp$MPIO_CDPMP)
## [1] "character"
munic_cereales=left_join(mun.tmp,alg_tol,by=c("MPIO_CDPMP"="COD_MUN"))
munic_cereales=munic_cereales %>% filter(DPTO_CNMBR=="TOLIMA") %>% na.omit()
breaks <- classIntervals(munic_cereales$max_prod, n = 6, style = 'fisher')
#label breaks
lab_vec <- vector(length = length(breaks$brks)-1)
rounded_breaks <- round(breaks$brks,2)
lab_vec[1] <- paste0('[', rounded_breaks[1],' - ', rounded_breaks[2],']')
for(i in 2:(length(breaks$brks) - 1)){
  lab_vec[i] <- paste0('(',rounded_breaks[i], ' - ', rounded_breaks[i+1], ']')}
munic_cereales <-  munic_cereales %>%
  mutate(faktor_class = factor(cut(max_prod, breaks$brks, include.lowest = T), labels = lab_vec))
# change attribute name
munic_cereales$Produccion = munic_cereales$faktor_class
# This code creates a new field ("mid") with centroid coordinates
munic_cereales$mid <- sf::st_centroid(munic_cereales$geometry)
# Get the longitude values
LONG = st_coordinates(munic_cereales$mid)[,1]
# Get the latitude values
LAT = st_coordinates(munic_cereales$mid)[,2]

5. Haz un mapa para el grupo de cultivos más importante

ggplot(data = munic_cereales) +
   geom_sf(aes(fill = Produccion)) +
   geom_label_repel(aes(x = LONG, y = LAT, label = MPIO_CNMBR), 
                    label.padding =     unit(0.05,"lines"),  
                    label.r = unit(0.025, "lines"),
                    label.size = 0.05) +
   geom_sf(aes(fill = Produccion)) +
   geom_label_repel(aes(x = LONG, y = LAT, label = MPIO_CNMBR), 
                    label.padding =     unit(0.05,"lines"),  
                    label.r = unit(0.025, "lines"),
                    label.size = 0.05)

6. Haz un nuevo mapa para el segundo grupo más grande de cultivos.

-Otra opción es producir un mapa interactivo:

# see example at https://r-tmap.github.io/tmap-book/layout.html
facet = "max_prod"
cereal_map =  
  tm_shape(munic_cereales) + tm_polygons(facet) + tm_text(text = "MPIO_CNMBR", size = 0.7, fontfamily = "sans") +
  tm_shape(tol.cities) + tm_symbols(shape = 2, col = "red", size = 0.20) +
  tm_credits("Data source: UPRA (2020)", fontface = "bold") +
  tm_layout(main.title = "Produccion de oleaginosas en 2020",
            main.title.fontface = "bold.italic", 
            legend.title.fontfamily = "monospace") +
  tm_scale_bar(position = c("left", "bottom"))
tmap_mode("view")
## tmap mode set to interactive viewing
cereal_map
## Credits not supported in view mode.
## Symbol shapes other than circles or icons are not supported in view mode.

7. Bibliografía

Cita en tu cuaderno este trabajo como Lizarazo, I., 2022. Comenzando con mapas temáticos. Disponible en https://rpubs.com/ials2un/thematic_maps_v2.

sessionInfo()
## R version 4.3.1 (2023-06-16 ucrt)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 11 x64 (build 22621)
## 
## Matrix products: default
## 
## 
## locale:
## [1] LC_COLLATE=Spanish_Mexico.utf8  LC_CTYPE=Spanish_Mexico.utf8   
## [3] LC_MONETARY=Spanish_Mexico.utf8 LC_NUMERIC=C                   
## [5] LC_TIME=Spanish_Mexico.utf8    
## 
## time zone: America/Bogota
## tzcode source: internal
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] ggrepel_0.9.3   ggplot2_3.4.3   classInt_0.4-10 tmap_3.3-4     
## [5] readxl_1.4.3    readr_2.1.4     dplyr_1.1.3     sf_1.0-14      
## 
## loaded via a namespace (and not attached):
##  [1] gtable_0.3.4             xfun_0.40                bslib_0.5.1             
##  [4] raster_3.6-23            htmlwidgets_1.6.2        lattice_0.21-8          
##  [7] tzdb_0.4.0               leaflet.providers_1.13.0 vctrs_0.6.3             
## [10] tools_4.3.1              crosstalk_1.2.0          generics_0.1.3          
## [13] parallel_4.3.1           tibble_3.2.1             proxy_0.4-27            
## [16] fansi_1.0.4              pkgconfig_2.0.3          KernSmooth_2.23-21      
## [19] RColorBrewer_1.1-3       leaflet_2.2.0            lifecycle_1.0.3         
## [22] farver_2.1.1             compiler_4.3.1           munsell_0.5.0           
## [25] terra_1.7-46             codetools_0.2-19         leafsync_0.1.0          
## [28] stars_0.6-4              htmltools_0.5.6          class_7.3-22            
## [31] sass_0.4.7               yaml_2.3.7               pillar_1.9.0            
## [34] crayon_1.5.2             jquerylib_0.1.4          ellipsis_0.3.2          
## [37] cachem_1.0.8             lwgeom_0.2-13            wk_0.8.0                
## [40] abind_1.4-5              mime_0.12                tidyselect_1.2.0        
## [43] digest_0.6.33            fastmap_1.1.1            grid_4.3.1              
## [46] colorspace_2.1-0         cli_3.6.1                magrittr_2.0.3          
## [49] base64enc_0.1-3          dichromat_2.0-0.1        XML_3.99-0.14           
## [52] utf8_1.2.3               leafem_0.2.3             e1071_1.7-13            
## [55] withr_2.5.1              scales_1.2.1             sp_2.1-0                
## [58] bit64_4.0.5              rmarkdown_2.25           bit_4.0.5               
## [61] cellranger_1.1.0         png_0.1-8                hms_1.1.3               
## [64] evaluate_0.22            knitr_1.44               tmaptools_3.1-1         
## [67] viridisLite_0.4.2        s2_1.1.4                 rlang_1.1.1             
## [70] Rcpp_1.0.11              glue_1.6.2               DBI_1.1.3               
## [73] rstudioapi_0.15.0        vroom_1.6.4              jsonlite_1.8.7          
## [76] R6_2.5.1                 units_0.8-4