En el cuaderno anterior se pudo obtener información particular para los grupos de cultivo más importantes para el departamento. Se elige en este caso tubérculos y plátanos como primer grupo, y el segundo corresponde a frutales. Si bien dicha información es relevante, por si sola no es muy útil, es por ello que se hace necesario asociarla a otro tipo de herramientas que permita su interpretación y posterior análisis. Este cuaderno, por tanto, tiene como objetivo, crear mapas que permitan visualizar la producción de dichos grupos de cultivo de acuerdo con los municipios del Guaviare.
En esta sección escribimos código para cargar todas las librerias que necesitamos
#library(tidyverse)
library(dplyr)
library(sf)
library(readr)
library(tmap)
library(ggplot2)
library(ggrepel)
library(classInt)
Cabe resaltar que en el escritorio de trabajo tiene que estar guardada la siguiente información:
Un archivo csv con las estadísticas EVA para el grupo de cultivo seleccionado
Un shapefile con las municipalidades del Guaviare
Un archivo csv con las ciudades de Colombia
Procedemos a leer los archivos por grupo de cultivo obtenidos con el cuaderno 1
(tuberculos_platano = read_csv("F:\\GBI\\GB2\\Ejerciciosr\\Cuaderno2\\guaviare_tuberculos_platano.csv", show_col_types = FALSE))
## # A tibble: 4 × 4
## COD_MUN MUNICIPIO GRUPO_CULTIVO produccion_maxima
## <dbl> <chr> <chr> <dbl>
## 1 95025 EL RETORNO TUBERCULOS Y PLATANOS 23688
## 2 95001 SAN JOSE DEL GUAVIARE TUBERCULOS Y PLATANOS 21984
## 3 95015 CALAMAR TUBERCULOS Y PLATANOS 13600
## 4 95200 MIRAFLORES TUBERCULOS Y PLATANOS 6828
Cabe resaltar que ya tenemos una tabla con los objetos espaciales necesarios para hacer el mapa con los municipios de nuestro departamento
munin<-st_read("F:\\GBI\\GB2\\Ejerciciosr\\Cuaderno2\\ADMINISTRATIVO\\MGN_MPIO_POLITICO.shp")
## Reading layer `MGN_MPIO_POLITICO' from data source
## `F:\GBI\GB2\Ejerciciosr\Cuaderno2\ADMINISTRATIVO\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
munin
## 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
## First 10 features:
## DPTO_CCDGO MPIO_CCDGO MPIO_CDPMP DPTO_CNMBR MPIO_CNMBR
## 1 05 001 05001 ANTIOQUIA MEDELLÍN
## 2 05 002 05002 ANTIOQUIA ABEJORRAL
## 3 05 004 05004 ANTIOQUIA ABRIAQUÍ
## 4 05 021 05021 ANTIOQUIA ALEJANDRÍA
## 5 05 030 05030 ANTIOQUIA AMAGÁ
## 6 05 031 05031 ANTIOQUIA AMALFI
## 7 05 034 05034 ANTIOQUIA ANDES
## 8 05 036 05036 ANTIOQUIA ANGELÓPOLIS
## 9 05 038 05038 ANTIOQUIA ANGOSTURA
## 10 05 040 05040 ANTIOQUIA ANORÍ
## MPIO_CRSLC MPIO_NAREA MPIO_CSMBL MPIO_VGNC
## 1 1965 374.81288 4 2021
## 2 1814 507.14109 4 2021
## 3 1912 296.89405 4 2021
## 4 Decreto departamental 304 de 1907 128.93215 4 2021
## 5 1912 84.13268 4 2021
## 6 1843 1209.14802 4 2021
## 7 1853 402.46597 4 2021
## 8 Ordenanza 16 del 12 de julio de 1896 81.87630 4 2021
## 9 1821 338.34813 4 2021
## 10 1821 1413.77572 4 2021
## MPIO_TIPO Shape_Leng Shape_Area geometry
## 1 MUNICIPIO 1.0325459 0.030605924 MULTIPOLYGON (((-75.66974 6...
## 2 MUNICIPIO 1.1585038 0.041383896 MULTIPOLYGON (((-75.46938 5...
## 3 MUNICIPIO 0.8121832 0.024248255 MULTIPOLYGON (((-76.08351 6...
## 4 MUNICIPIO 0.7051995 0.010534527 MULTIPOLYGON (((-75.0332 6....
## 5 MUNICIPIO 0.4452407 0.006866523 MULTIPOLYGON (((-75.67587 6...
## 6 MUNICIPIO 2.0633596 0.098921310 MULTIPOLYGON (((-74.92268 6...
## 7 MUNICIPIO 1.1469836 0.032816580 MULTIPOLYGON (((-75.86822 5...
## 8 MUNICIPIO 0.4274956 0.006683387 MULTIPOLYGON (((-75.69149 6...
## 9 MUNICIPIO 0.9156706 0.027666958 MULTIPOLYGON (((-75.27173 6...
## 10 MUNICIPIO 1.8476441 0.115706037 MULTIPOLYGON (((-74.90935 7...
mun_gua2021<-dplyr::filter(munin,DPTO_CNMBR == "GUAVIARE")
mun_gua2021
## Simple feature collection with 4 features and 12 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -73.66391 ymin: 0.6554126 xmax: -69.99511 ymax: 2.924987
## Geodetic CRS: MAGNA-SIRGAS
## DPTO_CCDGO MPIO_CCDGO MPIO_CDPMP DPTO_CNMBR MPIO_CNMBR
## 1 95 001 95001 GUAVIARE SAN JOSÉ DEL GUAVIARE
## 2 95 015 95015 GUAVIARE CALAMAR
## 3 95 025 95025 GUAVIARE EL RETORNO
## 4 95 200 95200 GUAVIARE MIRAFLORES
## MPIO_CRSLC MPIO_NAREA MPIO_CSMBL MPIO_VGNC
## 1 Decreto Nal 1165 del 7 de Junio de 1976 16757.07 4 2021
## 2 Ordenanza 001 del 7 de Agosto de 1992 13069.59 4 2021
## 3 Ordenanza 001 del 7 de Agosto de 1992 12909.12 4 2021
## 4 Ordenanza 001 del 7 de Agosto de 1992 12808.08 4 2021
## MPIO_TIPO Shape_Leng Shape_Area geometry
## 1 MUNICIPIO 14.085782 1.360391 MULTIPOLYGON (((-71.31266 2...
## 2 MUNICIPIO 7.529464 1.061812 MULTIPOLYGON (((-72.6716 2....
## 3 MUNICIPIO 12.315742 1.047240 MULTIPOLYGON (((-72.73135 2...
## 4 MUNICIPIO 7.385424 1.039462 MULTIPOLYGON (((-72.01357 1...
Puesto que solo se necesitan unos cuantos atributos, se procede a seleccionar lo que realmente se necesita de la tabla
mun_gua2021 %>% select(MPIO_CDPMP,MPIO_CNMBR,MPIO_NAREA)->municipios1
municipios1
## Simple feature collection with 4 features and 3 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -73.66391 ymin: 0.6554126 xmax: -69.99511 ymax: 2.924987
## Geodetic CRS: MAGNA-SIRGAS
## MPIO_CDPMP MPIO_CNMBR MPIO_NAREA geometry
## 1 95001 SAN JOSÉ DEL GUAVIARE 16757.07 MULTIPOLYGON (((-71.31266 2...
## 2 95015 CALAMAR 13069.59 MULTIPOLYGON (((-72.6716 2....
## 3 95025 EL RETORNO 12909.12 MULTIPOLYGON (((-72.73135 2...
## 4 95200 MIRAFLORES 12808.08 MULTIPOLYGON (((-72.01357 1...
Antes de continuar, es imprescindible conocer cual es el CRS de los datos obtenidos anteriormente;
st_crs(municipios1)
## 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]]
Ahora procedemos a leer el archivo csv de ciudades
cities<-read_csv("F:\\GBI\\GB2\\Ejerciciosr\\Cuaderno2\\co.csv")
## Rows: 1102 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.
cities
## # A tibble: 1,102 × 9
## city lat lng country iso2 admin_name capital popul…¹ popul…²
## <chr> <dbl> <dbl> <chr> <chr> <chr> <chr> <dbl> <dbl>
## 1 Bogotá 4.61 -74.1 Colombia CO Bogotá primary 9464000 7963000
## 2 Medellín 6.24 -75.6 Colombia CO Antioquia admin 2529403 2529403
## 3 Cali 3.44 -76.5 Colombia CO Valle del Ca… admin 2471474 2471474
## 4 Barranquilla 11.0 -74.8 Colombia CO Atlántico admin 1274250 1274250
## 5 Cartagena 10.4 -75.5 Colombia CO Bolívar admin 1036412 1036412
## 6 Soacha 4.58 -74.2 Colombia CO Cundinamarca minor 995268 995268
## 7 Palermo 2.89 -75.4 Colombia CO Huila minor 800000 800000
## 8 Cúcuta 7.91 -72.5 Colombia CO Norte de San… admin 750000 750000
## 9 Soledad 10.9 -74.8 Colombia CO Atlántico minor 698852 342556
## 10 Pereira 4.81 -75.7 Colombia CO Risaralda admin 590554 590554
## # … with 1,092 more rows, and abbreviated variable names ¹population,
## # ²population_proper
Puesto que la información almacenada no corresponde con objetos espaciales (es una tibble), se debe llevar a cabo el debido proceso para convertirla a dicho formato
sf.cities<-st_as_sf(x=cities,coords = c('lng','lat'))
sf.cities
## Simple feature collection with 1102 features and 7 fields
## Geometry type: POINT
## Dimension: XY
## Bounding box: xmin: -81.7006 ymin: -4.215 xmax: -67.4858 ymax: 13.3817
## CRS: NA
## # A tibble: 1,102 × 8
## city country iso2 admin…¹ capital popul…² popul…³ geometry
## <chr> <chr> <chr> <chr> <chr> <dbl> <dbl> <POINT>
## 1 Bogo… Colomb… CO Bogotá primary 9464000 7963000 (-74.0705 4.6126)
## 2 Mede… Colomb… CO Antioq… admin 2529403 2529403 (-75.5748 6.2447)
## 3 Cali Colomb… CO Valle … admin 2471474 2471474 (-76.5197 3.44)
## 4 Barr… Colomb… CO Atlánt… admin 1274250 1274250 (-74.7964 10.9639)
## 5 Cart… Colomb… CO Bolívar admin 1036412 1036412 (-75.5253 10.4236)
## 6 Soac… Colomb… CO Cundin… minor 995268 995268 (-74.2144 4.5781)
## 7 Pale… Colomb… CO Huila minor 800000 800000 (-75.4339 2.8883)
## 8 Cúcu… Colomb… CO Norte … admin 750000 750000 (-72.5047 7.9075)
## 9 Sole… Colomb… CO Atlánt… minor 698852 342556 (-74.77 10.92)
## 10 Pere… Colomb… CO Risara… admin 590554 590554 (-75.6946 4.8143)
## # … with 1,092 more rows, and abbreviated variable names ¹admin_name,
## # ²population, ³population_proper
Ahora se debe añadir CRS (sistema de coordenadas geográficas). Antes de continuar, se debe tener en cuenta la limitación que representa tener un sistema de coordenadas diferente en el archivo de municipios. Esto se debe a que si se va a hacer un joint, los datos quedarían con CRS distintos, por tanto se requiere hacer una conversión
Primero añadimos CRS al archivo de ciudades
st_crs(sf.cities)<-4326
Luego creamos un objeto con el CRS de municipios
new_crs<-4686
Ahora se le coloca este nuevo CRS a las ciudades
new.cities<-st_transform(sf.cities, new_crs)
new.cities
## Simple feature collection with 1102 features and 7 fields
## Geometry type: POINT
## Dimension: XY
## Bounding box: xmin: -81.7006 ymin: -4.215 xmax: -67.4858 ymax: 13.3817
## Geodetic CRS: MAGNA-SIRGAS
## # A tibble: 1,102 × 8
## city country iso2 admin…¹ capital popul…² popul…³ geometry
## * <chr> <chr> <chr> <chr> <chr> <dbl> <dbl> <POINT [°]>
## 1 Bogo… Colomb… CO Bogotá primary 9464000 7963000 (-74.0705 4.6126)
## 2 Mede… Colomb… CO Antioq… admin 2529403 2529403 (-75.5748 6.2447)
## 3 Cali Colomb… CO Valle … admin 2471474 2471474 (-76.5197 3.44)
## 4 Barr… Colomb… CO Atlánt… admin 1274250 1274250 (-74.7964 10.9639)
## 5 Cart… Colomb… CO Bolívar admin 1036412 1036412 (-75.5253 10.4236)
## 6 Soac… Colomb… CO Cundin… minor 995268 995268 (-74.2144 4.5781)
## 7 Pale… Colomb… CO Huila minor 800000 800000 (-75.4339 2.8883)
## 8 Cúcu… Colomb… CO Norte … admin 750000 750000 (-72.5047 7.9075)
## 9 Sole… Colomb… CO Atlánt… minor 698852 342556 (-74.77 10.92)
## 10 Pere… Colomb… CO Risara… admin 590554 590554 (-75.6946 4.8143)
## # … with 1,092 more rows, and abbreviated variable names ¹admin_name,
## # ²population, ³population_proper
Para esto se debe crear un spatial join, primero con todas las ciudades de todos los departamentos, en otras palabras, se debe ubicar primero a las ciudades -que son puntos- dentro de los municipios -que son polígonos-
sf.cities.joined<-st_join(new.cities,municipios1,join=st_within)
sf.cities.joined
## Simple feature collection with 1102 features and 10 fields
## Geometry type: POINT
## Dimension: XY
## Bounding box: xmin: -81.7006 ymin: -4.215 xmax: -67.4858 ymax: 13.3817
## Geodetic CRS: MAGNA-SIRGAS
## # A tibble: 1,102 × 11
## city country iso2 admin…¹ capital popul…² popul…³ geometry
## * <chr> <chr> <chr> <chr> <chr> <dbl> <dbl> <POINT [°]>
## 1 Bogo… Colomb… CO Bogotá primary 9464000 7963000 (-74.0705 4.6126)
## 2 Mede… Colomb… CO Antioq… admin 2529403 2529403 (-75.5748 6.2447)
## 3 Cali Colomb… CO Valle … admin 2471474 2471474 (-76.5197 3.44)
## 4 Barr… Colomb… CO Atlánt… admin 1274250 1274250 (-74.7964 10.9639)
## 5 Cart… Colomb… CO Bolívar admin 1036412 1036412 (-75.5253 10.4236)
## 6 Soac… Colomb… CO Cundin… minor 995268 995268 (-74.2144 4.5781)
## 7 Pale… Colomb… CO Huila minor 800000 800000 (-75.4339 2.8883)
## 8 Cúcu… Colomb… CO Norte … admin 750000 750000 (-72.5047 7.9075)
## 9 Sole… Colomb… CO Atlánt… minor 698852 342556 (-74.77 10.92)
## 10 Pere… Colomb… CO Risara… admin 590554 590554 (-75.6946 4.8143)
## # … with 1,092 more rows, 3 more variables: MPIO_CDPMP <chr>, MPIO_CNMBR <chr>,
## # MPIO_NAREA <dbl>, and abbreviated variable names ¹admin_name, ²population,
## # ³population_proper
Puesto que solo estamos interesados en el departamento del Guaviare, es necesario filtrar la información del archivo de ciudades únicamente para dicho departamento.
guav_cities<-dplyr::filter(sf.cities.joined,admin_name=='Guaviare')
guav_cities
## Simple feature collection with 4 features and 10 fields
## Geometry type: POINT
## Dimension: XY
## Bounding box: xmin: -72.6531 ymin: 1.3367 xmax: -71.9511 ymax: 2.5653
## Geodetic CRS: MAGNA-SIRGAS
## # A tibble: 4 × 11
## city country iso2 admin…¹ capital popul…² popul…³ geometry
## * <chr> <chr> <chr> <chr> <chr> <dbl> <dbl> <POINT [°]>
## 1 San J… Colomb… CO Guavia… admin 68878 68878 (-72.6386 2.5653)
## 2 El Re… Colomb… CO Guavia… minor 24562 24562 (-72.6278 2.3306)
## 3 Miraf… Colomb… CO Guavia… minor NA NA (-71.9511 1.3367)
## 4 Calam… Colomb… CO Guavia… minor NA NA (-72.6531 1.9596)
## # … with 3 more variables: MPIO_CDPMP <chr>, MPIO_CNMBR <chr>,
## # MPIO_NAREA <dbl>, and abbreviated variable names ¹admin_name, ²population,
## # ³population_proper
Particularmente se busca hacer un mapa coroplético con dicha información, para lo cual estaremos utilizando librerias como tmap, ggplot2 y classInt. Cabe recordar que la activación de estas librerias se encuentra en el apartado de configuración.
Como primer paso, se debe unir las estadísticas municipales y la tabla de municipios creada, sin embargo, se debe recordar que no tienen los mismos atributos. En ese sentido, para llevar a cabo la unión se hace necesario buscar al menos un atributo en común, particularmente el código de municipio. En principio se debe revisar si el tipo de datos de ambas tablas es el mismo
class(tuberculos_platano$COD_MUN)
## [1] "numeric"
class(municipios1$MPIO_CDPMP)
## [1] "character"
Para el caso del grupo de cultivo, este dato corresponde al tipo numérico, así que se debe convertir a caracter
(tuberculos_platano$COD_MUN = as.character(tuberculos_platano$COD_MUN))
## [1] "95025" "95001" "95015" "95200"
Ahora si se puede llevar a cabo la unión entre los municipios y el grupo de cultivo
mun_tp<-left_join(municipios1,tuberculos_platano,by=c('MPIO_CDPMP'='COD_MUN'))
mun_tp
## Simple feature collection with 4 features and 6 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -73.66391 ymin: 0.6554126 xmax: -69.99511 ymax: 2.924987
## Geodetic CRS: MAGNA-SIRGAS
## MPIO_CDPMP MPIO_CNMBR MPIO_NAREA MUNICIPIO
## 1 95001 SAN JOSÉ DEL GUAVIARE 16757.07 SAN JOSE DEL GUAVIARE
## 2 95015 CALAMAR 13069.59 CALAMAR
## 3 95025 EL RETORNO 12909.12 EL RETORNO
## 4 95200 MIRAFLORES 12808.08 MIRAFLORES
## GRUPO_CULTIVO produccion_maxima geometry
## 1 TUBERCULOS Y PLATANOS 21984 MULTIPOLYGON (((-71.31266 2...
## 2 TUBERCULOS Y PLATANOS 13600 MULTIPOLYGON (((-72.6716 2....
## 3 TUBERCULOS Y PLATANOS 23688 MULTIPOLYGON (((-72.73135 2...
## 4 TUBERCULOS Y PLATANOS 6828 MULTIPOLYGON (((-72.01357 1...
El siguiente código modifica los colores de los municipios de acuerdo con la producción máxima:
breaks <- classIntervals(mun_tp$produccion_maxima, n = 6, style = 'fisher')
## Warning in classIntervals(mun_tp$produccion_maxima, n = 6, style = "fisher"): n
## greater than number of different finite values\nn reset to number of different
## finite values
## Warning in classIntervals(mun_tp$produccion_maxima, n = 6, style = "fisher"): n
## same as number of different finite values\neach different finite value is a
## separate class
#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], ']')
}
Para crear el mapa hay que reproyectar municipios y ciudades al CRS 4326
# guav_cities <-st_transform(guav_cities, 4326)
municipios1<-st_transform(municipios1, 4326)
mun_tp <-st_transform(mun_tp, 4326)
mun_tp <- mun_tp %>%
mutate(faktor_class = factor(cut(produccion_maxima, breaks$brks, include.lowest = T), labels = lab_vec))
# Cambiar el nombre del atributo
mun_tp$Produccion = mun_tp$faktor_class
# Crear un espacio nuevo (en la mitad) con coordenas centroidales
mun_tp$mid <- sf::st_centroid(mun_tp$geometry)
mun_tp
## Simple feature collection with 4 features and 8 fields
## Active geometry column: geometry
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -73.66391 ymin: 0.6554126 xmax: -69.99511 ymax: 2.924987
## Geodetic CRS: WGS 84
## MPIO_CDPMP MPIO_CNMBR MPIO_NAREA MUNICIPIO
## 1 95001 SAN JOSÉ DEL GUAVIARE 16757.07 SAN JOSE DEL GUAVIARE
## 2 95015 CALAMAR 13069.59 CALAMAR
## 3 95025 EL RETORNO 12909.12 EL RETORNO
## 4 95200 MIRAFLORES 12808.08 MIRAFLORES
## GRUPO_CULTIVO produccion_maxima geometry
## 1 TUBERCULOS Y PLATANOS 21984 MULTIPOLYGON (((-71.31266 2...
## 2 TUBERCULOS Y PLATANOS 13600 MULTIPOLYGON (((-72.6716 2....
## 3 TUBERCULOS Y PLATANOS 23688 MULTIPOLYGON (((-72.73135 2...
## 4 TUBERCULOS Y PLATANOS 6828 MULTIPOLYGON (((-72.01357 1...
## faktor_class Produccion mid
## 1 (17792 - 22836] (17792 - 22836] POINT (-71.91807 2.484715)
## 2 (10214 - 17792] (10214 - 17792] POINT (-73.03837 1.59618)
## 3 (22836 - 26498] (22836 - 26498] POINT (-71.58567 2.086506)
## 4 [4018 - 10214] [4018 - 10214] POINT (-72.01812 1.363953)
# Obtención de los valores longitudinales
LONG = st_coordinates(mun_tp$mid)[,1]
#Obtención valores latitudinales
LAT = st_coordinates(mun_tp$mid)[,2]
ggplot(data = mun_tp) +
geom_sf(aes(fill = Produccion)) +
geom_label_repel(aes(x = LONG, y = LAT, label = MPIO_CNMBR),
label.padding = unit(0.10,"lines"),
label.r = unit(0.025, "lines"),
label.size = 0.05)
De igual modo, es necesario importar la información del directorio de trabajo del respectivo cuaderno
(frutales = read_csv("F:\\GBI\\GB2\\Ejerciciosr\\Cuaderno2\\guaviare_frutales.csv", show_col_types = FALSE))
## # A tibble: 4 × 4
## COD_MUN MUNICIPIO GRUPO_CULTIVO produccion_maxima
## <dbl> <chr> <chr> <dbl>
## 1 95001 SAN JOSE DEL GUAVIARE FRUTALES 5495
## 2 95025 EL RETORNO FRUTALES 4352
## 3 95015 CALAMAR FRUTALES 1925
## 4 95200 MIRAFLORES FRUTALES 1050
Cabe resaltar que al igual que con el grupo de cultivo anterior, es necesario seguir una serie de pasos. Primero debemos asegurarnos que el código de municipio se encuentre en formato de texto
class(frutales$COD_MUN)
## [1] "numeric"
frutales$COD_MUN=as.character(frutales$COD_MUN)
Unimos frutales con municipios
mun_fru<-left_join(municipios1,frutales,by=c('MPIO_CDPMP'='COD_MUN'))
mun_fru
## Simple feature collection with 4 features and 6 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: -73.66391 ymin: 0.6554126 xmax: -69.99511 ymax: 2.924987
## Geodetic CRS: WGS 84
## MPIO_CDPMP MPIO_CNMBR MPIO_NAREA MUNICIPIO
## 1 95001 SAN JOSÉ DEL GUAVIARE 16757.07 SAN JOSE DEL GUAVIARE
## 2 95015 CALAMAR 13069.59 CALAMAR
## 3 95025 EL RETORNO 12909.12 EL RETORNO
## 4 95200 MIRAFLORES 12808.08 MIRAFLORES
## GRUPO_CULTIVO produccion_maxima geometry
## 1 FRUTALES 5495 MULTIPOLYGON (((-71.31266 2...
## 2 FRUTALES 1925 MULTIPOLYGON (((-72.6716 2....
## 3 FRUTALES 4352 MULTIPOLYGON (((-72.73135 2...
## 4 FRUTALES 1050 MULTIPOLYGON (((-72.01357 1...
Hecho lo anterior, es posible hacer el mapa dinámico con el siguiente código
facet = "produccion_maxima"
mun_fru_map =
tm_shape(mun_fru) + tm_polygons(facet) + tm_text(text = "MPIO_CNMBR", size = 0.7, fontfamily = "sans") +
tm_shape(guav_cities) + tm_symbols(shape = 2, col = "red", size = 0.20) +
tm_credits("Data source: UPRA (2020)", fontface = "bold") +
tm_layout(main.title = "Produccion de frutales 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
mun_fru_map
## Credits not supported in view mode.
## Symbol shapes other than circles or icons are not supported in view mode.
Lizarazo, I., 2022. Getting started with thematic maps. Available at https://rpubs.com/ials2un/thematic_maps_v2.
sessionInfo()
## R version 4.2.2 (2022-10-31 ucrt)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 22621)
##
## Matrix products: default
##
## locale:
## [1] LC_COLLATE=English_United States.utf8
## [2] LC_CTYPE=English_United States.utf8
## [3] LC_MONETARY=English_United States.utf8
## [4] LC_NUMERIC=C
## [5] LC_TIME=English_United States.utf8
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] classInt_0.4-9 ggrepel_0.9.3 ggplot2_3.4.1 tmap_3.3-3 readr_2.1.4
## [6] sf_1.0-11 dplyr_1.1.0
##
## 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] sp_1.6-0 highr_0.10 yaml_2.3.7
## [10] pillar_1.8.1 lattice_0.20-45 glue_1.6.2
## [13] digest_0.6.31 RColorBrewer_1.1-3 colorspace_2.1-0
## [16] leaflet.providers_1.9.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.2 scales_1.2.1 terra_1.7-23
## [25] tzdb_0.3.0 tibble_3.1.8 proxy_0.4-27
## [28] generics_0.1.3 farver_2.1.1 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.2
## [43] hms_1.1.2 lifecycle_1.0.3 munsell_0.5.0
## [46] compiler_4.2.2 jquerylib_0.1.4 e1071_1.7-13
## [49] rlang_1.0.6 units_0.8-1 grid_4.2.2
## [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] gtable_0.3.1 codetools_0.2-18 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 parallel_4.2.2
## [73] Rcpp_1.0.10 vctrs_0.5.2 png_0.1-8
## [76] leaflet_2.1.2 tidyselect_1.2.0 xfun_0.37