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.

library(sf)
## Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE
library(readr)
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

3. LEER ARCHIVOS RELACIONADOS CON MUNICIPIOS, CULTIVOS Y CIUDADES

Trabajaré con el Departamento de Cundinamarca.

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:

list.files( pattern=c('csv'))
## [1] "ciudadesco.csv"              "CUN_tuberculos_2022.csv.csv"

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

(papa = read_csv("CUN_tuberculos_2022.csv.csv",show_col_types = FALSE))
## # A tibble: 102 × 4
##    COD_MUN MUNICIPIO        GRUPO               max_prod
##      <dbl> <chr>            <chr>                  <dbl>
##  1   25873 Villapinzón      Raíces y Tubérculos   174000
##  2   25793 Tausa            Raíces y Tubérculos   142120
##  3   25326 Guatavita        Raíces y Tubérculos    38400
##  4   25736 Sesquilé         Raíces y Tubérculos    32640
##  5   25899 Zipaquirá        Raíces y Tubérculos    32340
##  6   25183 Chocontá         Raíces y Tubérculos    29400
##  7   25377 La Calera        Raíces y Tubérculos    23400
##  8   25740 Sibaté           Raíces y Tubérculos    21150
##  9   25772 Suesca           Raíces y Tubérculos    20000
## 10   25154 Carmen de Carupa Raíces y Tubérculos    18750
## # ℹ 92 more rows

-El, lee los municipios de tu departamento:

(mun.tmp =  st_read("BM/MGN_MPIO_POLITICO.shp"))
## Reading layer `MGN_MPIO_POLITICO' from data source 
##   `C:\Users\SEBAS\Downloads\GB\BM\MGN_MPIO_POLITICO.shp' using driver `ESRI Shapefile'
## Simple feature collection with 1182 features and 11 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -81.73562 ymin: -4.229406 xmax: -66.84722 ymax: 13.39473
## Geodetic CRS:  WGS 84
## Simple feature collection with 1182 features and 11 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -81.73562 ymin: -4.229406 xmax: -66.84722 ymax: 13.39473
## Geodetic CRS:  WGS 84
## First 10 features:
##    DPTO_CCDGO MPIO_CCDGO             MPIO_CNMBR
## 1          18        001              FLORENCIA
## 2          18        029                ALBANIA
## 3          18        094 BELÉN DE LOS ANDAQUÍES
## 4          18        247            EL DONCELLO
## 5          18        256              EL PAUJÍL
## 6          18        410           LA MONTAÑITA
## 7          18        460                  MILÁN
## 8          18        479                MORELIA
## 9          18        610    SAN JOSÉ DEL FRAGUA
## 10         18        860             VALPARAÍSO
##                               MPIO_CRSLC MPIO_NAREA MPIO_CCNCT MPIO_NANO
## 1        Decreto 642 de Junio 17 de 1912  2547.6375      18001      2018
## 2    Ordenanza 3 de Noviembre 12 de 1985   414.1221      18029      2018
## 3        Decreto 963 de Marzo 14 de 1950  1191.6186      18094      2018
## 4   Decreto 1678 de Septiembre 7 de 1967  1106.0762      18247      2018
## 5  Decreto 1678 de Septiembret 7 de 1967  1234.7341      18256      2018
## 6          Decreto 83 de Julio 6 de 1955  1701.0614      18410      2018
## 7    Ordenanza 3 de Noviembre 12 de 1985  1220.5760      18460      2018
## 8    Ordenanza 3 de Noviembre 12 de 1985   462.4796      18479      2018
## 9    Ordenanza 3 de Noviembre 12 de 1985  1304.7690      18610      2018
## 10   Ordenanza 3 de Noviembre 12 de 1985  1330.2100      18860      2018
##    DPTO_CNMBR Shape_Leng Shape_Area ORIG_FID                       geometry
## 1     CAQUETÁ   2.942508 0.20692777        0 POLYGON ((-75.42074 2.19413...
## 2     CAQUETÁ   1.112829 0.03361758        1 POLYGON ((-75.89506 1.36569...
## 3     CAQUETÁ   2.234657 0.09674460        2 POLYGON ((-75.78705 1.74982...
## 4     CAQUETÁ   3.154370 0.08986744        3 POLYGON ((-75.36167 2.32142...
## 5     CAQUETÁ   3.529316 0.10030928        4 POLYGON ((-75.36638 2.20952...
## 6     CAQUETÁ   3.402939 0.13817351        5 POLYGON ((-75.40346 1.76845...
## 7     CAQUETÁ   1.863197 0.09912782        6 POLYGON ((-75.39362 1.35738...
## 8     CAQUETÁ   1.518688 0.03755356        7 POLYGON ((-75.77185 1.57991...
## 9     CAQUETÁ   2.040837 0.10589313        8 POLYGON ((-76.16722 1.58752...
## 10    CAQUETÁ   2.313848 0.10800551        9 POLYGON ((-75.73128 1.32740...

-Seleccionemos algunos atributos para limpiar el objeto:

mun.tmp %>% filter(DPTO_CNMBR=="CUNDINAMARCA") %>% select(MPIO_CCNCT , MPIO_CNMBR, MPIO_NAREA) -> municipios

-Ahora miremos el resultado:

municipios
## Simple feature collection with 117 features and 3 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -74.89063 ymin: 3.730129 xmax: -73.05256 ymax: 5.837258
## Geodetic CRS:  WGS 84
## First 10 features:
##    MPIO_CCNCT MPIO_CNMBR MPIO_NAREA                       geometry
## 1       25019      ALBÁN   50.83510 POLYGON ((-74.47852 4.95231...
## 2       25035   ANAPOIMA  123.95549 POLYGON ((-74.55201 4.64758...
## 3       25040   ANOLAIMA  120.95235 POLYGON ((-74.43043 4.84847...
## 4       25053   ARBELÁEZ  142.45997 POLYGON ((-74.42848 4.29270...
## 5       25086    BELTRÁN  176.84599 POLYGON ((-74.76139 4.84168...
## 6       25095    BITUIMA   61.04619 POLYGON ((-74.51062 4.94530...
## 7       25099     BOJACÁ  102.31988 POLYGON ((-74.32819 4.76302...
## 8       25120    CABRERA  421.83959 POLYGON ((-74.46463 4.03711...
## 9       25123   CACHIPAY   53.45262 POLYGON ((-74.40513 4.77414...
## 10      25126     CAJICÁ   51.27563 POLYGON ((-73.99959 4.98505...

-Ahora, lea el archivo csv de las ciudades:

ciudadesco=read.csv("ciudadesco.csv")
ciudadesco
##                      city     lat      lng  country iso2
## 1                  Bogotá  4.7111 -74.0722 Colombia   CO
## 2                  Timbío  2.3445 -76.6839 Colombia   CO
## 3                Medellín  6.2308 -75.5906 Colombia   CO
## 4                    Cali  3.4206 -76.5222 Colombia   CO
## 5            Barranquilla 10.9833 -74.8019 Colombia   CO
## 6               Cartagena 10.4000 -75.5000 Colombia   CO
## 7             Bucaramanga  7.1333 -73.0000 Colombia   CO
## 8                 Palermo  2.8917 -75.4375 Colombia   CO
## 9                  Cúcuta  7.8942 -72.5039 Colombia   CO
## 10                Soledad 10.9167 -74.7500 Colombia   CO
## 11          Villavicencio  4.1500 -73.6333 Colombia   CO
## 12                Pereira  4.8143 -75.6946 Colombia   CO
## 13             Valledupar 10.4833 -73.2500 Colombia   CO
## 14                 Ibagué  4.4333 -75.2333 Colombia   CO
## 15                 Soacha  4.5872 -74.2214 Colombia   CO
## 16            Santa Marta 11.2419 -74.2053 Colombia   CO
## 17               Montería  8.7500 -75.8833 Colombia   CO
## 18                  Bello  6.3333 -75.5667 Colombia   CO
## 19              Manizales  5.1000 -75.5500 Colombia   CO
## 20           Buenaventura  3.8772 -77.0267 Colombia   CO
## 21                  Pasto  1.2078 -77.2772 Colombia   CO
## 22                  Neiva  2.9345 -75.2809 Colombia   CO
## 23                Palmira  3.5833 -76.2500 Colombia   CO
## 24                 Zarzal  4.3983 -76.0772 Colombia   CO
## 25                Armenia  4.5300 -75.6800 Colombia   CO
## 26                Popayán  2.4542 -76.6092 Colombia   CO
## 27              Sincelejo  9.2950 -75.3961 Colombia   CO
## 28                 Itagüí  6.1667 -75.6167 Colombia   CO
## 29          Floridablanca  7.2167 -73.0667 Colombia   CO
## 30               Envigado  6.1667 -75.5667 Colombia   CO
## 31                  Tuluá  4.0833 -76.2000 Colombia   CO
## 32                 Tumaco  1.8067 -78.7647 Colombia   CO
## 33        Barrancabermeja  7.0667 -73.8500 Colombia   CO
## 34                  Uripa 11.9167 -72.0000 Colombia   CO
## 35              Zipaquirá  5.0333 -74.0000 Colombia   CO
## 36              Florencia  1.6139 -75.6128 Colombia   CO
## 37                  Turbo  8.1000 -76.7333 Colombia   CO
## 38           Dosquebradas  4.8333 -75.6833 Colombia   CO
## 39               Ríohacha 11.5442 -72.9069 Colombia   CO
## 40                Ipiales  0.8303 -77.6444 Colombia   CO
## 41                  Tunja  5.5333 -73.3667 Colombia   CO
## 42                  Girón  7.0731 -73.1681 Colombia   CO
## 43                  Yopal  5.3500 -72.4100 Colombia   CO
## 44             Fusagasugá  4.3452 -74.3618 Colombia   CO
## 45               Rionegro  6.1535 -75.3743 Colombia   CO
## 46                Cartago  4.7000 -75.9167 Colombia   CO
## 47               Pitalito  1.8989 -76.0419 Colombia   CO
## 48                 Quibdó  5.6922 -76.6581 Colombia   CO
## 49               Girardot  4.3050 -74.8017 Colombia   CO
## 50                Ciénaga 11.0069 -74.2500 Colombia   CO
## 51                Malambo 10.8500 -74.7500 Colombia   CO
## 52               Mosquera  4.7078 -74.2328 Colombia   CO
## 53                Duitama  5.8333 -73.0167 Colombia   CO
## 54               Magangué  9.2500 -74.7667 Colombia   CO
## 55                 Maicao 11.3778 -72.2389 Colombia   CO
## 56               Apartadó  7.8833 -76.6333 Colombia   CO
## 57                 Uribia 11.7139 -72.2658 Colombia   CO
## 58            Piedecuesta  7.0833 -73.0000 Colombia   CO
## 59             Facatativá  4.8167 -74.3667 Colombia   CO
## 60    Guadalajara de Buga  3.9000 -76.3019 Colombia   CO
## 61 Santander de Quilichao  3.0167 -76.4833 Colombia   CO
## 62                Turbaco 10.3500 -75.3333 Colombia   CO
## 63               Sogamoso  5.7167 -72.9208 Colombia   CO
## 64                 Madrid  4.7344 -74.2683 Colombia   CO
## 65              Aguachica  8.3167 -73.6333 Colombia   CO
## 66            Sabanalarga  6.8500 -75.8167 Colombia   CO
## 67                   Chía  4.8500 -74.0500 Colombia   CO
## 68                 Arauca  7.0903 -70.7617 Colombia   CO
## 69                  Funza  4.7167 -74.2167 Colombia   CO
## 70               Sabaneta  6.1500 -75.6000 Colombia   CO
## 71             Copacabana  6.3333 -75.5000 Colombia   CO
## 72             San Andrés 12.5847 -81.7006 Colombia   CO
## 73            La Estrella  6.1667 -75.6667 Colombia   CO
## 74  San José del Guaviare  2.5667 -72.6333 Colombia   CO
## 75                  Mocoa  1.1500 -76.6475 Colombia   CO
## 76                 Cajicá  4.9167 -74.0333 Colombia   CO
## 77    La Jagua de Ibirico  9.5667 -73.3333 Colombia   CO
## 78                Leticia -4.2167 -69.9333 Colombia   CO
## 79            La Virginia  4.9167 -75.8333 Colombia   CO
## 80                   Mitú  1.1983 -70.1733 Colombia   CO
## 81                Inírida  3.8653 -67.9239 Colombia   CO
## 82         Puerto Carreño  6.1833 -67.4667 Colombia   CO
##                  admin_name capital population population_proper
## 1                    Bogotá primary    7968095         7743955.0
## 2                     Cauca   minor    4444444         4444444.0
## 3                 Antioquia   admin    2529403         2529403.0
## 4           Valle del Cauca   admin    2471474         2471474.0
## 5                 Atlántico   admin    1326588         1274250.0
## 6                   Bolívar   admin    1036412         1036412.0
## 7                 Santander   admin     870752          581130.0
## 8                     Huila   minor     800000          800000.0
## 9        Norte de Santander   admin     750000          750000.0
## 10                Atlántico   minor     698852          455796.0
## 11                     Meta   admin     664148          664148.0
## 12                Risaralda   admin     590554          590554.0
## 13                    Cesar   admin     544134          544134.0
## 14                   Tolima   admin     541101          541101.0
## 15             Cundinamarca   minor     522442          522442.0
## 16                Magdalena   admin     515556          515556.0
## 17                  Córdoba   admin     505334          505334.0
## 18                Antioquia   minor     495483          371591.0
## 19                   Caldas   admin     434403          434403.0
## 20          Valle del Cauca   minor     423927          423927.0
## 21                   Nariño   admin     392930          392930.0
## 22                    Huila   admin     353033          353033.0
## 23          Valle del Cauca   minor     349294          349294.0
## 24          Valle del Cauca   minor     312599          312599.0
## 25                  Quindío   admin     301226          301226.0
## 26                    Cauca   admin     300837          300837.0
## 27                    Sucre   admin     286716          286716.0
## 28                Antioquia   minor     276744          276744.0
## 29                Santander   minor     267170          267170.0
## 30                Antioquia   minor     228848          228848.0
## 31          Valle del Cauca   minor     219138          219138.0
## 32                   Nariño   minor     212692          212692.0
## 33                Santander   minor     210729          210729.0
## 34               La Guajira             198890          198890.0
## 35             Cundinamarca   minor     196409          196409.0
## 36                  Caquetá   admin     191867          191867.0
## 37                Antioquia   minor     181000          181000.0
## 38                Risaralda   minor     179301          179301.0
## 39               La Guajira   admin     167865          167865.0
## 40                   Nariño   minor     166079          166079.0
## 41                   Boyacá   admin     163894             409.5
## 42                Santander   minor     160403          160403.0
## 43                 Casanare   admin     143619          106822.0
## 44             Cundinamarca   minor     139805          139805.0
## 45                Antioquia   minor     135465          135465.0
## 46          Valle del Cauca   minor     134972          134972.0
## 47                    Huila   minor     133205          133205.0
## 48                    Chocó   admin     130825          130825.0
## 49             Cundinamarca   minor     129834          129834.0
## 50                Magdalena   minor     129414          129414.0
## 51                Atlántico   minor     129148          129148.0
## 52             Cundinamarca   minor     128012           91282.0
## 53                   Boyacá   minor     126670          126670.0
## 54                  Bolívar   minor     123906          123906.0
## 55               La Guajira   minor     123757          123757.0
## 56                Antioquia   minor     121003          121003.0
## 57               La Guajira   minor     117674          117674.0
## 58                Santander   minor     117364          117364.0
## 59             Cundinamarca   minor     117133          117133.0
## 60          Valle del Cauca   minor     116893          116893.0
## 61                    Cauca   minor     116535          116535.0
## 62                  Bolívar   minor     115000          115000.0
## 63                   Boyacá   minor     114486          114486.0
## 64             Cundinamarca   minor     112254          112254.0
## 65                    Cesar   minor     109621          109621.0
## 66                Antioquia   minor     102334          102334.0
## 67             Cundinamarca   minor      97896           97896.0
## 68                   Arauca   admin      96814           96814.0
## 69             Cundinamarca   minor      90671           80937.0
## 70                Antioquia   minor      82375           82375.0
## 71                Antioquia   minor      73574           73574.0
## 72 San Andrés y Providencia   admin      71946           71946.0
## 73                Antioquia   minor      71545           71545.0
## 74                 Guaviare   admin      68878           68878.0
## 75                 Putumayo   admin      56398           56398.0
## 76             Cundinamarca   minor      54111           44721.0
## 77                    Cesar   minor      46722           46722.0
## 78                 Amazonas   admin      32450           32450.0
## 79                Risaralda   minor      32330           32330.0
## 80                   Vaupés   admin      28382           28382.0
## 81                  Guainía   admin      19816           19816.0
## 82                  Vichada   admin      16763           16763.0

-Tenga en cuenta que hay 82 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):

sf.cities <-  st_as_sf(x = ciudadesco, 
                        coords = c("lng", "lat"))
sf.cities
## Simple feature collection with 82 features and 7 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: -81.7006 ymin: -4.2167 xmax: -67.4667 ymax: 12.5847
## CRS:           NA
## First 10 features:
##            city  country iso2         admin_name capital population
## 1        Bogotá Colombia   CO             Bogotá primary    7968095
## 2        Timbío Colombia   CO              Cauca   minor    4444444
## 3      Medellín Colombia   CO          Antioquia   admin    2529403
## 4          Cali Colombia   CO    Valle del Cauca   admin    2471474
## 5  Barranquilla Colombia   CO          Atlántico   admin    1326588
## 6     Cartagena Colombia   CO            Bolívar   admin    1036412
## 7   Bucaramanga Colombia   CO          Santander   admin     870752
## 8       Palermo Colombia   CO              Huila   minor     800000
## 9        Cúcuta Colombia   CO Norte de Santander   admin     750000
## 10      Soledad Colombia   CO          Atlántico   minor     698852
##    population_proper                 geometry
## 1            7743955  POINT (-74.0722 4.7111)
## 2            4444444  POINT (-76.6839 2.3445)
## 3            2529403  POINT (-75.5906 6.2308)
## 4            2471474  POINT (-76.5222 3.4206)
## 5            1274250 POINT (-74.8019 10.9833)
## 6            1036412       POINT (-75.5 10.4)
## 7             581130       POINT (-73 7.1333)
## 8             800000  POINT (-75.4375 2.8917)
## 9             750000  POINT (-72.5039 7.8942)
## 10            455796   POINT (-74.75 10.9167)

-¡Tenga en cuenta el CRS que falta!

Agreguemos el CRS usando el código EPSG:

st_crs(sf.cities) <- 4326
#st_crs(municipios)=4326

4. Subconjunto de datos relevantes para nuestro departamento.

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

sf.cities.joined <- st_join(sf.cities, municipios, join = st_within)
Cun.cities=filter(sf.cities.joined,admin_name=="Cundinamarca")

-Para mostrar el objeto unido:

sf.cities.joined
## Simple feature collection with 82 features and 10 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: -81.7006 ymin: -4.2167 xmax: -67.4667 ymax: 12.5847
## Geodetic CRS:  WGS 84
## First 10 features:
##            city  country iso2         admin_name capital population
## 1        Bogotá Colombia   CO             Bogotá primary    7968095
## 2        Timbío Colombia   CO              Cauca   minor    4444444
## 3      Medellín Colombia   CO          Antioquia   admin    2529403
## 4          Cali Colombia   CO    Valle del Cauca   admin    2471474
## 5  Barranquilla Colombia   CO          Atlántico   admin    1326588
## 6     Cartagena Colombia   CO            Bolívar   admin    1036412
## 7   Bucaramanga Colombia   CO          Santander   admin     870752
## 8       Palermo Colombia   CO              Huila   minor     800000
## 9        Cúcuta Colombia   CO Norte de Santander   admin     750000
## 10      Soledad Colombia   CO          Atlántico   minor     698852
##    population_proper MPIO_CCNCT MPIO_CNMBR MPIO_NAREA                 geometry
## 1            7743955       <NA>       <NA>         NA  POINT (-74.0722 4.7111)
## 2            4444444       <NA>       <NA>         NA  POINT (-76.6839 2.3445)
## 3            2529403       <NA>       <NA>         NA  POINT (-75.5906 6.2308)
## 4            2471474       <NA>       <NA>         NA  POINT (-76.5222 3.4206)
## 5            1274250       <NA>       <NA>         NA POINT (-74.8019 10.9833)
## 6            1036412       <NA>       <NA>         NA       POINT (-75.5 10.4)
## 7             581130       <NA>       <NA>         NA       POINT (-73 7.1333)
## 8             800000       <NA>       <NA>         NA  POINT (-75.4375 2.8917)
## 9             750000       <NA>       <NA>         NA  POINT (-72.5039 7.8942)
## 10            455796       <NA>       <NA>         NA   POINT (-74.75 10.9167)

Tenga en cuenta que obtuvimos un marco de datos sf con cada fila de ciudades adjuntadas con las columnas de nuestros municipios. Las ciudades ubicadas en un departamento diferente tienen muchas NA.

Ahora filtramos las filas que corresponden a nuestro departamento (en este caso Cundinamarca):

cundi.cities = dplyr::filter(sf.cities.joined, admin_name=='CUNDINAMARCA')
cundi.cities
## Simple feature collection with 0 features and 10 fields
## Bounding box:  xmin: NA ymin: NA xmax: NA ymax: NA
## Geodetic CRS:  WGS 84
##  [1] city              country           iso2              admin_name       
##  [5] capital           population        population_proper MPIO_CCNCT       
##  [9] MPIO_CNMBR        MPIO_NAREA        geometry         
## <0 rows> (or 0-length row.names)

5. HAZ UN MAPA PARA EL GRUPO DE CULTIVOS MÁS IMPORTANTES.

-Ahora, haz un mapa coroplético de estos datos. Usaremos las bibliotecas tmap, ggplot2 y classInt.

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(ggplot2)
library(ggrepel)
library(classInt)

-Recordemos que el objeto municipios no tiene atributos EVA. En cambio, el objeto frutales, que contiene estadísticas de cultivos, es un objeto no espacial. Nuestra siguiente tarea es unir el objeto de estadísticas a los objetos espaciales para tener los datos relevantes en un solo objeto.

Para poder realizar la unión, necesitamos una clave compartida, es decir, un atributo común. En este caso lo tenemos en ambos objetos, ese es el código municipal. Sin embargo, tenga en cuenta que tanto sus nombres como sus tipos de datos son diferentes.

class(papa$COD_MUN)
## [1] "numeric"
class(papa$max_prod)
## [1] "numeric"
class(municipios$MPIO_CCNCT)
## [1] "character"

-Por lo tanto, necesitamos arreglar esto:

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

-Ahora estamos listos para unirnos. Es posible que necesites revisar tus notas de clase para entender lo que sucede aquí:

head(papa)
## # A tibble: 6 × 4
##   COD_MUN MUNICIPIO   GRUPO               max_prod
##   <chr>   <chr>       <chr>                  <dbl>
## 1 25873   Villapinzón Raíces y Tubérculos   174000
## 2 25793   Tausa       Raíces y Tubérculos   142120
## 3 25326   Guatavita   Raíces y Tubérculos    38400
## 4 25736   Sesquilé    Raíces y Tubérculos    32640
## 5 25899   Zipaquirá   Raíces y Tubérculos    32340
## 6 25183   Chocontá    Raíces y Tubérculos    29400
head(municipios)
## Simple feature collection with 6 features and 3 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -74.8191 ymin: 4.175736 xmax: -74.23773 ymax: 4.952534
## Geodetic CRS:  WGS 84
##   MPIO_CCNCT MPIO_CNMBR MPIO_NAREA                       geometry
## 1      25019      ALBÁN   50.83510 POLYGON ((-74.47852 4.95231...
## 2      25035   ANAPOIMA  123.95549 POLYGON ((-74.55201 4.64758...
## 3      25040   ANOLAIMA  120.95235 POLYGON ((-74.43043 4.84847...
## 4      25053   ARBELÁEZ  142.45997 POLYGON ((-74.42848 4.29270...
## 5      25086    BELTRÁN  176.84599 POLYGON ((-74.76139 4.84168...
## 6      25095    BITUIMA   61.04619 POLYGON ((-74.51062 4.94530...
municipios$MPIO_CDPMP= as.character(municipios$MPIO_CCNCT)
class(municipios$MPIO_CDPMP)
## [1] "character"
munic_papa = left_join(municipios, papa, by = c("MPIO_CCNCT" = "COD_MUN"))
munic_papa
## Simple feature collection with 117 features and 7 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -74.89063 ymin: 3.730129 xmax: -73.05256 ymax: 5.837258
## Geodetic CRS:  WGS 84
## First 10 features:
##    MPIO_CCNCT MPIO_CNMBR MPIO_NAREA MPIO_CDPMP MUNICIPIO               GRUPO
## 1       25019      ALBÁN   50.83510      25019     Albán Raíces y Tubérculos
## 2       25035   ANAPOIMA  123.95549      25035  Anapoima Raíces y Tubérculos
## 3       25040   ANOLAIMA  120.95235      25040      <NA>                <NA>
## 4       25053   ARBELÁEZ  142.45997      25053  Arbeláez Raíces y Tubérculos
## 5       25086    BELTRÁN  176.84599      25086   Beltrán Raíces y Tubérculos
## 6       25095    BITUIMA   61.04619      25095   Bituima Raíces y Tubérculos
## 7       25099     BOJACÁ  102.31988      25099    Bojacá Raíces y Tubérculos
## 8       25120    CABRERA  421.83959      25120   Cabrera Raíces y Tubérculos
## 9       25123   CACHIPAY   53.45262      25123      <NA>                <NA>
## 10      25126     CAJICÁ   51.27563      25126    Cajicá Raíces y Tubérculos
##    max_prod                       geometry
## 1     220.0 POLYGON ((-74.47852 4.95231...
## 2     640.0 POLYGON ((-74.55201 4.64758...
## 3        NA POLYGON ((-74.43043 4.84847...
## 4     266.1 POLYGON ((-74.42848 4.29270...
## 5     315.0 POLYGON ((-74.76139 4.84168...
## 6      35.0 POLYGON ((-74.51062 4.94530...
## 7    5044.5 POLYGON ((-74.32819 4.76302...
## 8     397.3 POLYGON ((-74.46463 4.03711...
## 9        NA POLYGON ((-74.40513 4.77414...
## 10    330.0 POLYGON ((-73.99959 4.98505...
munic_papa <- munic_papa %>% replace(is.na(.),0)
head(munic_papa)
## Simple feature collection with 6 features and 7 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -74.8191 ymin: 4.175736 xmax: -74.23773 ymax: 4.952534
## Geodetic CRS:  WGS 84
##   MPIO_CCNCT MPIO_CNMBR MPIO_NAREA MPIO_CDPMP MUNICIPIO               GRUPO
## 1      25019      ALBÁN   50.83510      25019     Albán Raíces y Tubérculos
## 2      25035   ANAPOIMA  123.95549      25035  Anapoima Raíces y Tubérculos
## 3      25040   ANOLAIMA  120.95235      25040         0                   0
## 4      25053   ARBELÁEZ  142.45997      25053  Arbeláez Raíces y Tubérculos
## 5      25086    BELTRÁN  176.84599      25086   Beltrán Raíces y Tubérculos
## 6      25095    BITUIMA   61.04619      25095   Bituima Raíces y Tubérculos
##   max_prod                       geometry
## 1    220.0 POLYGON ((-74.47852 4.95231...
## 2    640.0 POLYGON ((-74.55201 4.64758...
## 3      0.0 POLYGON ((-74.43043 4.84847...
## 4    266.1 POLYGON ((-74.42848 4.29270...
## 5    315.0 POLYGON ((-74.76139 4.84168...
## 6     35.0 POLYGON ((-74.51062 4.94530...

Tenga en cuenta que munic_papa incluye ahora el atributo max_prod que representa la cantidad total de toneladas producidas por cultivos de papa en 2020.

El siguiente código personaliza los colores de los municipios. Más información [aquí] (https://stackoverflow.com/questions/57177312/trying-to-plot-in-tmap-shapefile-with-attribute).

breaks<- classIntervals(munic_papa$max_prod, n = 6, style = 'fisher')
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_papa <-  munic_papa %>%
  mutate(faktor_class = factor(cut(max_prod, breaks$brks, include.lowest = T), labels = lab_vec))
# Cambiar el nombre del atributo
munic_papa$Produccion = munic_papa$faktor_class
# Este código crea un nuevo campo ("medio") con coordenadas centroides
munic_papa$mid <- sf::st_centroid(munic_papa$geometry)
LONG = st_coordinates(munic_papa$mid)[,1]
LAT = st_coordinates(munic_papa$mid)[,2]
ggplot(data = munic_papa) +
   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)
## Warning: ggrepel: 91 unlabeled data points (too many overlaps). Consider
## increasing max.overlaps

facet = "Produccion"
Ht_map =  
  tm_shape(munic_papa) + tm_polygons(facet) + tm_text(text = "MUNICIPIO", size = 0.7, fontfamily = "sans") +
  tm_shape(municipios) + tm_symbols(shape = 2, col = "red", size = 0.20) +
  tm_credits("Data source: UPRA (2020)", fontface = "bold") +
  tm_layout(main.title = "Produccion de papa 2022",
            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
Ht_map
## Credits not supported in view mode.
## Symbol shapes other than circles or icons are not supported in view mode.

6. HAZ UN NUEVO MAPA PARA EL SEGUNDO GRUPO MÁS GRANDE DE CULTIVOS.

-Otra opción es producir un mapa interactivo:

facet = "max_prod"
papa_map =  
  tm_shape(munic_papa) + tm_polygons(facet) + tm_text(text = "MPIO_CNMBR", size = 0.7, fontfamily = "sans") +
  tm_shape(Cun.cities) + tm_symbols(shape = 2, col = "red", size = 0.20) +
  tm_credits("Data source: UPRA (2020)", fontface = "bold") +
  tm_layout(main.title = "Produccion de papa 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
papa_map
## Credits not supported in view mode.
## Symbol shapes other than circles or icons are not supported in view mode.

7. BIBLIOGRAFÍA

Lizarazo, I., 2022. 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 10 x64 (build 19045)
## 
## 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    
## 
## time zone: America/Bogota
## tzcode source: internal
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] classInt_0.4-10 ggrepel_0.9.4   ggplot2_3.4.3   tmap_3.3-4     
## [5] dplyr_1.1.3     readr_2.1.4     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              highr_0.10               pkgconfig_2.0.3         
## [19] KernSmooth_2.23-21       RColorBrewer_1.1-3       leaflet_2.2.0           
## [22] lifecycle_1.0.3          farver_2.1.1             compiler_4.3.1          
## [25] munsell_0.5.0            terra_1.7-55             codetools_0.2-19        
## [28] leafsync_0.1.0           stars_0.6-4              htmltools_0.5.6         
## [31] class_7.3-22             sass_0.4.7               yaml_2.3.7              
## [34] pillar_1.9.0             crayon_1.5.2             jquerylib_0.1.4         
## [37] ellipsis_0.3.2           cachem_1.0.8             lwgeom_0.2-13           
## [40] wk_0.8.0                 abind_1.4-5              mime_0.12               
## [43] tidyselect_1.2.0         digest_0.6.33            fastmap_1.1.1           
## [46] grid_4.3.1               colorspace_2.1-0         cli_3.6.1               
## [49] magrittr_2.0.3           base64enc_0.1-3          dichromat_2.0-0.1       
## [52] XML_3.99-0.14            utf8_1.2.3               leafem_0.2.3            
## [55] e1071_1.7-13             withr_2.5.0              scales_1.2.1            
## [58] sp_2.1-0                 bit64_4.0.5              rmarkdown_2.24          
## [61] bit_4.0.5                png_0.1-8                hms_1.1.3               
## [64] evaluate_0.21            knitr_1.43               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.3              jsonlite_1.8.7          
## [76] R6_2.5.1                 units_0.8-3