rm(list=ls())

1. Introducción

En el departamento del Meta, se tienen los dos cultivos más grandes pertenecientes a este territorio. El primero se clasifica como otros permanentes (Son aquellos que tienen una duración de más de una temporada, es decir, se siembran o plantan una vez, y se pueden cosechar durante varias temporadas), dichos cultivos pueden estar compuestos tanto de frutales como de arboles maderables y plantas ornamentales. El segundo cultivo abarca los cereales, tales como el arroz, el maiz, el trigo, entre otros. Dichos cultivos corresponden a la mayor parte de la producción del departamento, por lo que el objetivo de este cuaderno es realizar mapas tematicos que representen a cuanto equivale esa producción y como se distribuye a traves de todo el territorio del Meta.

2. Instalar y cargar las librerias

Durante el desarrollo de este cuaderno, se requiere tener instaladas y cargadas las siguientes librerias.

library(sf)
library(dplyr)
library(readr)
library(tidyverse)

3. Leer los archivos relacionados con municipios, cultivos y ciudades.

list.files("C:/GB2/CUADERNO_1", pattern = c("csv"))
## [1] "CEREALES2018.csv" "co.csv"           "COL_cities.csv"   "EVA.csv"         
## [5] "OTROS2018.csv"
(OTROS2018 = read_csv("C:/GB2/CUADERNO_1/OTROS2018.csv",show_col_types = FALSE))
## # A tibble: 29 × 4
##    COD_MUN MUNICIPIO            GRUPO_CULTIVO     max_prod
##      <dbl> <chr>                <chr>                <dbl>
##  1   50573 PUERTO LOPEZ         OTROS PERMANENTES  2315889
##  2   50330 MESETAS              OTROS PERMANENTES     1646
##  3   50400 LEJANIAS             OTROS PERMANENTES     1430
##  4   50350 LA MACARENA          OTROS PERMANENTES      900
##  5   50711 VISTA HERMOSA        OTROS PERMANENTES      794
##  6   50313 GRANADA              OTROS PERMANENTES      621
##  7   50245 EL CALVARIO          OTROS PERMANENTES      600
##  8   50370 LA URIBE             OTROS PERMANENTES      520
##  9   50686 SAN JUANITO          OTROS PERMANENTES      416
## 10   50223 SAN LUIS DE CUBARRAL OTROS PERMANENTES      408
## # ℹ 19 more rows
(mun.tmp =  st_read("C:/GB2/CUADERNO_1/DATOS_CUADERNO_2/MUNI_META.gpkg"))
## Reading layer `MUNI_META' from data source 
##   `C:\GB2\CUADERNO_1\DATOS_CUADERNO_2\MUNI_META.gpkg' using driver `GPKG'
## Simple feature collection with 29 features and 10 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -74.89921 ymin: 1.604238 xmax: -71.07753 ymax: 4.899101
## Geodetic CRS:  MAGNA-SIRGAS
## Simple feature collection with 29 features and 10 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -74.89921 ymin: 1.604238 xmax: -71.07753 ymax: 4.899101
## Geodetic CRS:  MAGNA-SIRGAS
## First 10 features:
##    DPTO_CCDGO MPIO_CCDGO             MPIO_CNMBR MPIO_CDPMP VERSION       AREA
## 1          50        001          VILLAVICENCIO      50001    2018 1285879354
## 2          50        006          ACACÃ\u008dAS      50006    2018 1123737929
## 3          50        110 BARRANCA DE UPÃ\u008dA      50110    2018  403818863
## 4          50        124               CABUYARO      50124    2018  913662509
## 5          50        150      CASTILLA LA NUEVA      50150    2018  514685967
## 6          50        223               CUBARRAL      50223    2018 1157865246
## 7          50        226                CUMARAL      50226    2018  625092446
## 8          50        245            EL CALVARIO      50245    2018  277851648
## 9          50        251            EL CASTILLO      50251    2018  568218056
## 10         50        270              EL DORADO      50270    2018  117341083
##     LATITUD  LONGITUD Shape_Leng  Shape_Area                           geom
## 1  4.091669 -73.49292  2.0397750 0.104714061 MULTIPOLYGON (((-73.69288 4...
## 2  4.009644 -73.72391  2.0742072 0.091507447 MULTIPOLYGON (((-73.80268 4...
## 3  4.519076 -72.99549  1.3120177 0.032894411 MULTIPOLYGON (((-73.01607 4...
## 4  4.315245 -72.95269  2.0088484 0.074403262 MULTIPOLYGON (((-73.08865 4...
## 5  3.805154 -73.53887  1.3493293 0.041899616 MULTIPOLYGON (((-73.7252 3....
## 6  3.828242 -74.07530  2.0750915 0.094269993 MULTIPOLYGON (((-74.20143 4...
## 7  4.232526 -73.31478  1.8712144 0.050908971 MULTIPOLYGON (((-73.55407 4...
## 8  4.353770 -73.71442  0.8050930 0.022635573 MULTIPOLYGON (((-73.74639 4...
## 9  3.615625 -73.88801  1.1179992 0.046251583 MULTIPOLYGON (((-73.92004 3...
## 10 3.706970 -73.83162  0.4364058 0.009552168 MULTIPOLYGON (((-73.83554 3...

3.1 Se cambian los nombres de los atributos

Una vez teniendo el objeto creado “mun.tmp”, es conveniente cambiarle los nombres para una mejor comprension de los datos.

mun.tmp
## Simple feature collection with 29 features and 10 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -74.89921 ymin: 1.604238 xmax: -71.07753 ymax: 4.899101
## Geodetic CRS:  MAGNA-SIRGAS
## First 10 features:
##    DPTO_CCDGO MPIO_CCDGO             MPIO_CNMBR MPIO_CDPMP VERSION       AREA
## 1          50        001          VILLAVICENCIO      50001    2018 1285879354
## 2          50        006          ACACÃ\u008dAS      50006    2018 1123737929
## 3          50        110 BARRANCA DE UPÃ\u008dA      50110    2018  403818863
## 4          50        124               CABUYARO      50124    2018  913662509
## 5          50        150      CASTILLA LA NUEVA      50150    2018  514685967
## 6          50        223               CUBARRAL      50223    2018 1157865246
## 7          50        226                CUMARAL      50226    2018  625092446
## 8          50        245            EL CALVARIO      50245    2018  277851648
## 9          50        251            EL CASTILLO      50251    2018  568218056
## 10         50        270              EL DORADO      50270    2018  117341083
##     LATITUD  LONGITUD Shape_Leng  Shape_Area                           geom
## 1  4.091669 -73.49292  2.0397750 0.104714061 MULTIPOLYGON (((-73.69288 4...
## 2  4.009644 -73.72391  2.0742072 0.091507447 MULTIPOLYGON (((-73.80268 4...
## 3  4.519076 -72.99549  1.3120177 0.032894411 MULTIPOLYGON (((-73.01607 4...
## 4  4.315245 -72.95269  2.0088484 0.074403262 MULTIPOLYGON (((-73.08865 4...
## 5  3.805154 -73.53887  1.3493293 0.041899616 MULTIPOLYGON (((-73.7252 3....
## 6  3.828242 -74.07530  2.0750915 0.094269993 MULTIPOLYGON (((-74.20143 4...
## 7  4.232526 -73.31478  1.8712144 0.050908971 MULTIPOLYGON (((-73.55407 4...
## 8  4.353770 -73.71442  0.8050930 0.022635573 MULTIPOLYGON (((-73.74639 4...
## 9  3.615625 -73.88801  1.1179992 0.046251583 MULTIPOLYGON (((-73.92004 3...
## 10 3.706970 -73.83162  0.4364058 0.009552168 MULTIPOLYGON (((-73.83554 3...

Con el siguiente código se revisan los nombres originales.

names(mun.tmp)
##  [1] "DPTO_CCDGO" "MPIO_CCDGO" "MPIO_CNMBR" "MPIO_CDPMP" "VERSION"   
##  [6] "AREA"       "LATITUD"    "LONGITUD"   "Shape_Leng" "Shape_Area"
## [11] "geom"

se cambian los nombres originales a unos más precisos para una mejor interpretacion.

nombres = c("DPTO_CCDGO","MNPIO_COD","MNPIO","MPIO_CDPMP","VER","AREA_KM2","LAT","LON","SHAPE_LENGHT","SHAPE_AREA","geom")

Estos son los nuevos nombres de los atributos de “mun.tmp”.

(names(mun.tmp)= nombres)
##  [1] "DPTO_CCDGO"   "MNPIO_COD"    "MNPIO"        "MPIO_CDPMP"   "VER"         
##  [6] "AREA_KM2"     "LAT"          "LON"          "SHAPE_LENGHT" "SHAPE_AREA"  
## [11] "geom"
mun.tmp
## Simple feature collection with 29 features and 10 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -74.89921 ymin: 1.604238 xmax: -71.07753 ymax: 4.899101
## Geodetic CRS:  MAGNA-SIRGAS
## First 10 features:
##    DPTO_CCDGO MNPIO_COD                  MNPIO MPIO_CDPMP  VER   AREA_KM2
## 1          50       001          VILLAVICENCIO      50001 2018 1285879354
## 2          50       006          ACACÃ\u008dAS      50006 2018 1123737929
## 3          50       110 BARRANCA DE UPÃ\u008dA      50110 2018  403818863
## 4          50       124               CABUYARO      50124 2018  913662509
## 5          50       150      CASTILLA LA NUEVA      50150 2018  514685967
## 6          50       223               CUBARRAL      50223 2018 1157865246
## 7          50       226                CUMARAL      50226 2018  625092446
## 8          50       245            EL CALVARIO      50245 2018  277851648
## 9          50       251            EL CASTILLO      50251 2018  568218056
## 10         50       270              EL DORADO      50270 2018  117341083
##         LAT       LON SHAPE_LENGHT  SHAPE_AREA                           geom
## 1  4.091669 -73.49292    2.0397750 0.104714061 MULTIPOLYGON (((-73.69288 4...
## 2  4.009644 -73.72391    2.0742072 0.091507447 MULTIPOLYGON (((-73.80268 4...
## 3  4.519076 -72.99549    1.3120177 0.032894411 MULTIPOLYGON (((-73.01607 4...
## 4  4.315245 -72.95269    2.0088484 0.074403262 MULTIPOLYGON (((-73.08865 4...
## 5  3.805154 -73.53887    1.3493293 0.041899616 MULTIPOLYGON (((-73.7252 3....
## 6  3.828242 -74.07530    2.0750915 0.094269993 MULTIPOLYGON (((-74.20143 4...
## 7  4.232526 -73.31478    1.8712144 0.050908971 MULTIPOLYGON (((-73.55407 4...
## 8  4.353770 -73.71442    0.8050930 0.022635573 MULTIPOLYGON (((-73.74639 4...
## 9  3.615625 -73.88801    1.1179992 0.046251583 MULTIPOLYGON (((-73.92004 3...
## 10 3.706970 -73.83162    0.4364058 0.009552168 MULTIPOLYGON (((-73.83554 3...

Se une el código del departamento con el codigo del municipio.

mun.tmp$DPTO_CCDGO = "50"

Al unir los dos códigos, se crea un objeto nuevo el cual se llamará “mun.tmp2”.

mun.tmp %>% unite(CODIGO, c("DPTO_CCDGO", "MNPIO_COD"), sep = "") -> mun.tmp2
mun.tmp2
## Simple feature collection with 29 features and 9 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -74.89921 ymin: 1.604238 xmax: -71.07753 ymax: 4.899101
## Geodetic CRS:  MAGNA-SIRGAS
## First 10 features:
##    CODIGO                  MNPIO MPIO_CDPMP  VER   AREA_KM2      LAT       LON
## 1   50001          VILLAVICENCIO      50001 2018 1285879354 4.091669 -73.49292
## 2   50006          ACACÃ\u008dAS      50006 2018 1123737929 4.009644 -73.72391
## 3   50110 BARRANCA DE UPÃ\u008dA      50110 2018  403818863 4.519076 -72.99549
## 4   50124               CABUYARO      50124 2018  913662509 4.315245 -72.95269
## 5   50150      CASTILLA LA NUEVA      50150 2018  514685967 3.805154 -73.53887
## 6   50223               CUBARRAL      50223 2018 1157865246 3.828242 -74.07530
## 7   50226                CUMARAL      50226 2018  625092446 4.232526 -73.31478
## 8   50245            EL CALVARIO      50245 2018  277851648 4.353770 -73.71442
## 9   50251            EL CASTILLO      50251 2018  568218056 3.615625 -73.88801
## 10  50270              EL DORADO      50270 2018  117341083 3.706970 -73.83162
##    SHAPE_LENGHT  SHAPE_AREA                           geom
## 1     2.0397750 0.104714061 MULTIPOLYGON (((-73.69288 4...
## 2     2.0742072 0.091507447 MULTIPOLYGON (((-73.80268 4...
## 3     1.3120177 0.032894411 MULTIPOLYGON (((-73.01607 4...
## 4     2.0088484 0.074403262 MULTIPOLYGON (((-73.08865 4...
## 5     1.3493293 0.041899616 MULTIPOLYGON (((-73.7252 3....
## 6     2.0750915 0.094269993 MULTIPOLYGON (((-74.20143 4...
## 7     1.8712144 0.050908971 MULTIPOLYGON (((-73.55407 4...
## 8     0.8050930 0.022635573 MULTIPOLYGON (((-73.74639 4...
## 9     1.1179992 0.046251583 MULTIPOLYGON (((-73.92004 3...
## 10    0.4364058 0.009552168 MULTIPOLYGON (((-73.83554 3...

El siguiente paso consiste en seleccionar solo los atributos con los cuales llevaremos a cabo el cuaderno. Esto también con el objetivo de “limpiar” el objeto y poder manejarlo más fácil. El nuevo objeto correponderá al nombre de “municipios”.

mun.tmp2 %>% select("CODIGO", "MNPIO", "AREA_KM2","geom") -> municipios
municipios
## Simple feature collection with 29 features and 3 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -74.89921 ymin: 1.604238 xmax: -71.07753 ymax: 4.899101
## Geodetic CRS:  MAGNA-SIRGAS
## First 10 features:
##    CODIGO                  MNPIO   AREA_KM2                           geom
## 1   50001          VILLAVICENCIO 1285879354 MULTIPOLYGON (((-73.69288 4...
## 2   50006          ACACÃ\u008dAS 1123737929 MULTIPOLYGON (((-73.80268 4...
## 3   50110 BARRANCA DE UPÃ\u008dA  403818863 MULTIPOLYGON (((-73.01607 4...
## 4   50124               CABUYARO  913662509 MULTIPOLYGON (((-73.08865 4...
## 5   50150      CASTILLA LA NUEVA  514685967 MULTIPOLYGON (((-73.7252 3....
## 6   50223               CUBARRAL 1157865246 MULTIPOLYGON (((-74.20143 4...
## 7   50226                CUMARAL  625092446 MULTIPOLYGON (((-73.55407 4...
## 8   50245            EL CALVARIO  277851648 MULTIPOLYGON (((-73.74639 4...
## 9   50251            EL CASTILLO  568218056 MULTIPOLYGON (((-73.92004 3...
## 10  50270              EL DORADO  117341083 MULTIPOLYGON (((-73.83554 3...

Posteriormente se lee el archivo de ciudades.csv, en este caso el nombre del archivo es co.csv.

(ciudades = read_csv("C:/GB2/CUADERNO_1/co.csv"))
## Rows: 1104 Columns: 9
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (5): city, country, iso2, admin_name, capital
## dbl (4): lat, lng, population, population_proper
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
## # A tibble: 1,104 × 9
##    city           lat   lng country  iso2  admin_name         capital population
##    <chr>        <dbl> <dbl> <chr>    <chr> <chr>              <chr>        <dbl>
##  1 Bogotá        4.71 -74.1 Colombia CO    Bogotá             primary    7968095
##  2 Timbío        2.34 -76.7 Colombia CO    Cauca              minor      4444444
##  3 Medellín      6.23 -75.6 Colombia CO    Antioquia          admin      2529403
##  4 Cali          3.42 -76.5 Colombia CO    Valle del Cauca    admin      2471474
##  5 Barranquilla 11.0  -74.8 Colombia CO    Atlántico          admin      1326588
##  6 Cartagena    10.4  -75.5 Colombia CO    Bolívar            admin      1036412
##  7 Bucaramanga   7.13 -73   Colombia CO    Santander          admin       870752
##  8 Palermo       2.89 -75.4 Colombia CO    Huila              minor       800000
##  9 Cúcuta        7.89 -72.5 Colombia CO    Norte de Santander admin       750000
## 10 Soledad      10.9  -74.8 Colombia CO    Atlántico          minor       698852
## # ℹ 1,094 more rows
## # ℹ 1 more variable: population_proper <dbl>

Este siguiente paso consiste en convertir las ciudades a objetos espaciales debido a que originalmente las ciudades son objetos NO espaciales en el archivo co.csv.

sf.ciudades <-  st_as_sf(x = ciudades, 
                        coords = c("lng", "lat"))
sf.ciudades
## Simple feature collection with 1104 features and 7 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: -81.7006 ymin: -4.2167 xmax: -67.4667 ymax: 13.3817
## CRS:           NA
## # A tibble: 1,104 × 8
##    city         country  iso2  admin_name   capital population population_proper
##    <chr>        <chr>    <chr> <chr>        <chr>        <dbl>             <dbl>
##  1 Bogotá       Colombia CO    Bogotá       primary    7968095           7743955
##  2 Timbío       Colombia CO    Cauca        minor      4444444           4444444
##  3 Medellín     Colombia CO    Antioquia    admin      2529403           2529403
##  4 Cali         Colombia CO    Valle del C… admin      2471474           2471474
##  5 Barranquilla Colombia CO    Atlántico    admin      1326588           1274250
##  6 Cartagena    Colombia CO    Bolívar      admin      1036412           1036412
##  7 Bucaramanga  Colombia CO    Santander    admin       870752            581130
##  8 Palermo      Colombia CO    Huila        minor       800000            800000
##  9 Cúcuta       Colombia CO    Norte de Sa… admin       750000            750000
## 10 Soledad      Colombia CO    Atlántico    minor       698852            455796
## # ℹ 1,094 more rows
## # ℹ 1 more variable: geometry <POINT>

Agregar el CRS usando el códido EPSG.

st_crs(sf.ciudades) <- 4326

Establecer el tipo de datos que se usarán durante el desarrollo del cuaderno para que estos sean iguales.

municipios<- st_transform(municipios, crs =  4326) 

4. Datos relevantes del departamento

Como se está trabajando con un solo departamento, se requiere crear un “spatial join”.

sf.ciudades.joined <- st_join(sf.ciudades, municipios, join = st_within)

Se ve el nuevo objeto creado, en el cual se encuentran las principales ciudades de Colombia.

sf.ciudades.joined
## Simple feature collection with 1104 features and 10 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: -81.7006 ymin: -4.2167 xmax: -67.4667 ymax: 13.3817
## Geodetic CRS:  WGS 84
## # A tibble: 1,104 × 11
##    city         country  iso2  admin_name   capital population population_proper
##  * <chr>        <chr>    <chr> <chr>        <chr>        <dbl>             <dbl>
##  1 Bogotá       Colombia CO    Bogotá       primary    7968095           7743955
##  2 Timbío       Colombia CO    Cauca        minor      4444444           4444444
##  3 Medellín     Colombia CO    Antioquia    admin      2529403           2529403
##  4 Cali         Colombia CO    Valle del C… admin      2471474           2471474
##  5 Barranquilla Colombia CO    Atlántico    admin      1326588           1274250
##  6 Cartagena    Colombia CO    Bolívar      admin      1036412           1036412
##  7 Bucaramanga  Colombia CO    Santander    admin       870752            581130
##  8 Palermo      Colombia CO    Huila        minor       800000            800000
##  9 Cúcuta       Colombia CO    Norte de Sa… admin       750000            750000
## 10 Soledad      Colombia CO    Atlántico    minor       698852            455796
## # ℹ 1,094 more rows
## # ℹ 4 more variables: geometry <POINT [°]>, CODIGO <chr>, MNPIO <chr>,
## #   AREA_KM2 <dbl>

Ahora, se filtran los datos que pertenecen al departamento trabajado, en este caso Meta.

ciudades_meta = dplyr::filter(sf.ciudades.joined, admin_name=='Meta')

El nuevo objeto que se creará, se llamará “ciudades_meta” y estará compuesto por los datos que corresponden a las ciudades del Meta.

ciudades_meta
## Simple feature collection with 29 features and 10 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: -74.3536 ymin: 2.1828 xmax: -72.0825 ymax: 4.5833
## Geodetic CRS:  WGS 84
## # A tibble: 29 × 11
##    city            country iso2  admin_name capital population population_proper
##  * <chr>           <chr>   <chr> <chr>      <chr>        <dbl>             <dbl>
##  1 Villavicencio   Colomb… CO    Meta       admin       664148            664148
##  2 Acacías         Colomb… CO    Meta       minor        75252             75252
##  3 Puerto Gaitán   Colomb… CO    Meta       minor        41017             41017
##  4 La Macarena     Colomb… CO    Meta       minor        36781             36781
##  5 Puerto López    Colomb… CO    Meta       minor        35097             35097
##  6 San Martín      Colomb… CO    Meta       minor        25902             25902
##  7 Vistahermosa    Colomb… CO    Meta       minor        25461             25461
##  8 Puerto Concord… Colomb… CO    Meta       minor        23131             23131
##  9 Cumaral         Colomb… CO    Meta       minor        21397             21397
## 10 Restrepo        Colomb… CO    Meta       minor        17610             17610
## # ℹ 19 more rows
## # ℹ 4 more variables: geometry <POINT [°]>, CODIGO <chr>, MNPIO <chr>,
## #   AREA_KM2 <dbl>

5. Realizar un mapa para el grupo de cultivos mas importante del departamento.

Como primer paso, se deben instalar las siguientes librerias. (“tmap”) (“ggplot2”) (“classInt”)

library(tmap)
## Warning: package 'tmap' was built under R version 4.2.3
library(ggplot2)
library(ggrepel)
## Warning: package 'ggrepel' was built under R version 4.2.3
library(classInt)
## Warning: package 'classInt' was built under R version 4.2.3

Para poder realizar la unión de los datos, se necesita que los datos requeridos (Codigo de municipio),se encuentren en un mismo tipo de datos, en este caso se cambiarán a un tipo “integer”.

class(OTROS2018$COD_MUN)
## [1] "numeric"
class(municipios$CODIGO)
## [1] "character"
OTROS2018$COD_MUN = as.integer(OTROS2018$COD_MUN)

Con el siguiente código, se ejecuta la transicion de tipo “character” a tipo “integer”

municipios$MNPIO_CCDGO = as.integer(municipios$CODIGO)

Una vez se tengan los datos en un mismo tipo, se puede ejecutar el proceso de union de el atributo (codigo de municipio) para los archivos: municipios y OTROS2018.Proceso donde se unen:

munic_otros2018 = left_join(municipios, OTROS2018, by = c("MNPIO_CCDGO" = "COD_MUN"))

Resultado de la unión:

munic_otros2018
## Simple feature collection with 29 features and 7 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -74.89921 ymin: 1.604238 xmax: -71.07753 ymax: 4.899101
## Geodetic CRS:  WGS 84
## First 10 features:
##    CODIGO                  MNPIO   AREA_KM2 MNPIO_CCDGO            MUNICIPIO
## 1   50001          VILLAVICENCIO 1285879354       50001        VILLAVICENCIO
## 2   50006          ACACÃ\u008dAS 1123737929       50006              ACACIAS
## 3   50110 BARRANCA DE UPÃ\u008dA  403818863       50110     BARRANCA DE UPIA
## 4   50124               CABUYARO  913662509       50124             CABUYARO
## 5   50150      CASTILLA LA NUEVA  514685967       50150    CASTILLA LA NUEVA
## 6   50223               CUBARRAL 1157865246       50223 SAN LUIS DE CUBARRAL
## 7   50226                CUMARAL  625092446       50226              CUMARAL
## 8   50245            EL CALVARIO  277851648       50245          EL CALVARIO
## 9   50251            EL CASTILLO  568218056       50251          EL CASTILLO
## 10  50270              EL DORADO  117341083       50270            EL DORADO
##        GRUPO_CULTIVO max_prod                           geom
## 1  OTROS PERMANENTES      142 MULTIPOLYGON (((-73.69288 4...
## 2  OTROS PERMANENTES      196 MULTIPOLYGON (((-73.80268 4...
## 3  OTROS PERMANENTES       39 MULTIPOLYGON (((-73.01607 4...
## 4  OTROS PERMANENTES       38 MULTIPOLYGON (((-73.08865 4...
## 5  OTROS PERMANENTES       83 MULTIPOLYGON (((-73.7252 3....
## 6  OTROS PERMANENTES      408 MULTIPOLYGON (((-74.20143 4...
## 7  OTROS PERMANENTES       41 MULTIPOLYGON (((-73.55407 4...
## 8  OTROS PERMANENTES      600 MULTIPOLYGON (((-73.74639 4...
## 9  OTROS PERMANENTES      309 MULTIPOLYGON (((-73.92004 3...
## 10 OTROS PERMANENTES      238 MULTIPOLYGON (((-73.83554 3...

El siguiente código, permite perzonalizar los colores de los municipios.

breaks <- classIntervals(munic_otros2018$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], ']')
}

Ahora, el mapa estático:

munic_otros2018 <-  munic_otros2018 %>%
  mutate(faktor_class = factor(cut(max_prod, breaks$brks, include.lowest = T), labels = lab_vec))
# Cambiar el nombre del atributo
munic_otros2018$Produccion = munic_otros2018$faktor_class

Este codigo, permite crear un nuevo campo “mid” con las coordenadas de los centroides.

munic_otros2018$mid <- sf::st_centroid(munic_otros2018$geom)

El siguiente paso es obtener los valores de longitud (LONG).

LONG = st_coordinates(munic_otros2018$mid)[,1]

Ahora, obtener los valores de latitud (LAT)

LAT = st_coordinates(munic_otros2018$mid)[,2]

Se cambia el atributo MUN a MUN1

mun.tmp$MUN -> MUN1

El resultado del mapa estático:

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

6. Realizar un mapa interactivo para el segundo tipo de cultivo más importante del departamento.

En este paso, se usarán los datos de EVA para los “cereales” el cual corresponde al segundo grupo de cultivo mas importante del Meta.

Para esto, se realizan pasos similares a los que se realizaron durante la elaboración del primer mapa.

(cereales_2018 = read_csv("C:/GB2/CUADERNO_1/CEREALES2018.csv",show_col_types = FALSE))
## # A tibble: 27 × 4
##    COD_MUN MUNICIPIO     GRUPO_CULTIVO max_prod
##      <dbl> <chr>         <chr>            <dbl>
##  1   50568 PUERTO GAITAN CEREALES        184534
##  2   50287 FUENTE DE ORO CEREALES         48823
##  3   50573 PUERTO LOPEZ  CEREALES         43209
##  4   50001 VILLAVICENCIO CEREALES         33307
##  5   50313 GRANADA       CEREALES         19322
##  6   50226 CUMARAL       CEREALES         16388
##  7   50124 CABUYARO      CEREALES         14104
##  8   50577 PUERTO LLERAS CEREALES         11291
##  9   50711 VISTA HERMOSA CEREALES          7923
## 10   50606 RESTREPO      CEREALES          6617
## # ℹ 17 more rows

Se cambia el tipo de datos de código de municipio a “character”.

cereales_2018$COD_MUN = as.character(cereales_2018$COD_MUN)

Se unen el atributo “código de municipo” de los archivos municipios y cereales_2018. El nuevo objeto el cual será el resultado de la unión se denominará munii_cereales_2018.

munic_cereales_2018 = left_join(municipios, cereales_2018, by = c("CODIGO" = "COD_MUN"))

El resultado es el siguiente:

munic_cereales_2018
## Simple feature collection with 29 features and 7 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -74.89921 ymin: 1.604238 xmax: -71.07753 ymax: 4.899101
## Geodetic CRS:  WGS 84
## First 10 features:
##    CODIGO                  MNPIO   AREA_KM2 MNPIO_CCDGO         MUNICIPIO
## 1   50001          VILLAVICENCIO 1285879354       50001     VILLAVICENCIO
## 2   50006          ACACÃ\u008dAS 1123737929       50006           ACACIAS
## 3   50110 BARRANCA DE UPÃ\u008dA  403818863       50110  BARRANCA DE UPIA
## 4   50124               CABUYARO  913662509       50124          CABUYARO
## 5   50150      CASTILLA LA NUEVA  514685967       50150 CASTILLA LA NUEVA
## 6   50223               CUBARRAL 1157865246       50223              <NA>
## 7   50226                CUMARAL  625092446       50226           CUMARAL
## 8   50245            EL CALVARIO  277851648       50245       EL CALVARIO
## 9   50251            EL CASTILLO  568218056       50251       EL CASTILLO
## 10  50270              EL DORADO  117341083       50270         EL DORADO
##    GRUPO_CULTIVO max_prod                           geom
## 1       CEREALES    33307 MULTIPOLYGON (((-73.69288 4...
## 2       CEREALES     2684 MULTIPOLYGON (((-73.80268 4...
## 3       CEREALES      923 MULTIPOLYGON (((-73.01607 4...
## 4       CEREALES    14104 MULTIPOLYGON (((-73.08865 4...
## 5       CEREALES     3674 MULTIPOLYGON (((-73.7252 3....
## 6           <NA>       NA MULTIPOLYGON (((-74.20143 4...
## 7       CEREALES    16388 MULTIPOLYGON (((-73.55407 4...
## 8       CEREALES      153 MULTIPOLYGON (((-73.74639 4...
## 9       CEREALES     3550 MULTIPOLYGON (((-73.92004 3...
## 10      CEREALES      356 MULTIPOLYGON (((-73.83554 3...

Ahora el mapa interactivo del cultivo de cereales:

facet = "max_prod"
cereales_2018_map =  
  tm_shape(munic_cereales_2018) + tm_polygons(facet) + tm_text(text = "MNPIO", size = 0.7, fontfamily = "sans") +
  tm_shape(ciudades_meta) + tm_symbols(shape = 2, col = "red", size = 0.20) +
  tm_credits("Data source: UPRA (2020)", fontface = "bold") +
  tm_layout(main.title = "Produccion de cereales en 2018",
            main.title.fontface = "bold.italic", 
            legend.title.fontfamily = "monospace") +
  tm_scale_bar(position = c("left", "bottom"))

Resultado del mapa:

tmap_mode("view")
## tmap mode set to interactive viewing
cereales_2018_map
## Credits not supported in view mode.
## Symbol shapes other than circles or icons are not supported in view mode.

7. Bibliografía

Para la elaboración de este cuaderno se usó: - Lizarazo, I., 2022. Getting started with thematic maps. Available at https://rpubs.com/ials2un/thematic_maps_v2 - MGN2018 Integrado con CNPV2018, nivel de Municipio

sessionInfo()
## R version 4.2.1 Patched (2022-09-21 r82893 ucrt)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 22621)
## 
## Matrix products: default
## 
## 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    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] classInt_0.4-9  ggrepel_0.9.3   tmap_3.3-3      lubridate_1.9.2
##  [5] forcats_1.0.0   stringr_1.5.0   purrr_1.0.1     tidyr_1.3.0    
##  [9] tibble_3.2.0    ggplot2_3.4.2   tidyverse_2.0.0 readr_2.1.4    
## [13] dplyr_1.1.2     sf_1.0-12      
## 
## loaded via a namespace (and not attached):
##  [1] sass_0.4.5              bit64_4.0.5             vroom_1.6.1            
##  [4] jsonlite_1.8.4          viridisLite_0.4.1       bslib_0.4.2            
##  [7] highr_0.10              sp_1.6-0                yaml_2.3.7             
## [10] lattice_0.20-45         pillar_1.9.0            glue_1.6.2             
## [13] digest_0.6.31           RColorBrewer_1.1-3      leaflet.providers_1.9.0
## [16] colorspace_2.1-0        htmltools_0.5.4         XML_3.99-0.14          
## [19] pkgconfig_2.0.3         raster_3.6-20           stars_0.6-1            
## [22] s2_1.1.3                scales_1.2.1            terra_1.7-29           
## [25] tzdb_0.3.0              timechange_0.2.0        proxy_0.4-27           
## [28] farver_2.1.1            generics_0.1.3          ellipsis_0.3.2         
## [31] cachem_1.0.7            withr_2.5.0             leafsync_0.1.0         
## [34] cli_3.6.0               mime_0.12               magrittr_2.0.3         
## [37] crayon_1.5.2            evaluate_0.20           fansi_1.0.4            
## [40] lwgeom_0.2-11           class_7.3-20            tools_4.2.1            
## [43] hms_1.1.2               lifecycle_1.0.3         munsell_0.5.0          
## [46] compiler_4.2.1          jquerylib_0.1.4         e1071_1.7-13           
## [49] rlang_1.1.0             units_0.8-2             grid_4.2.1             
## [52] tmaptools_3.1-1         dichromat_2.0-0.1       rstudioapi_0.14        
## [55] htmlwidgets_1.6.2       crosstalk_1.2.0         leafem_0.2.0           
## [58] base64enc_0.1-3         rmarkdown_2.20          wk_0.7.2               
## [61] codetools_0.2-18        gtable_0.3.1            abind_1.4-5            
## [64] DBI_1.1.3               markdown_1.5            R6_2.5.1               
## [67] knitr_1.42              fastmap_1.1.1           bit_4.0.5              
## [70] utf8_1.2.3              KernSmooth_2.23-20      stringi_1.7.12         
## [73] parallel_4.2.1          Rcpp_1.0.10             png_0.1-8              
## [76] vctrs_0.6.0             leaflet_2.1.2           tidyselect_1.2.0       
## [79] xfun_0.37