#1. mapa tematico partipacion municipal de los dos grupos de cultivos mas importantes en el departamento del meta.

##.2 Instalacion de paquetes y librerias.

#install.packages("tmap")
#install.packages("ggplot2")
#install.packages("classInt")
library(readxl)
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
library(s2)
library(sf)
## Linking to GEOS 3.9.1, GDAL 3.2.1, PROJ 7.2.1; sf_use_s2() is TRUE

###.3 lectura de datos.

list.files("C:\\Users\\PERSONAL\\Documents\\cuaderno1y2", pattern=c('csv'))
## [1] "co.csv"                                        
## [2] "Evaluaciones_Agropecuarias_Municipales_EVA.csv"
## [3] "meta_Cereales_2020.csv"                        
## [4] "meta_Platanos_2020.csv"                        
## [5] "meta_Plátanos_2020.csv"
list.files("C:\\Users\\PERSONAL\\Documents\\cuaderno1y2")
##  [1] "20210624_BaseSIPRA2020.xlsx"                   
##  [2] "co.csv"                                        
##  [3] "Cuaderno1.html"                                
##  [4] "Cuaderno1.Rmd"                                 
##  [5] "cuaderno2.html"                                
##  [6] "cuaderno2.Rmd"                                 
##  [7] "Evaluaciones_Agropecuarias_Municipales_EVA.csv"
##  [8] "meta_Cereales_2020.csv"                        
##  [9] "meta_Platanos_2020.csv"                        
## [10] "meta_Plátanos_2020.csv"                        
## [11] "META3116.shp"                                  
## [12] "MGN_MPIO_POLITICO.CPG"                         
## [13] "MGN_MPIO_POLITICO.dbf"                         
## [14] "MGN_MPIO_POLITICO.prj"                         
## [15] "MGN_MPIO_POLITICO.sbn"                         
## [16] "MGN_MPIO_POLITICO.sbx"                         
## [17] "MGN_MPIO_POLITICO.shp"                         
## [18] "MGN_MPIO_POLITICO.shp.xml"                     
## [19] "MGN_MPIO_POLITICO.shx"                         
## [20] "MUNICIPIOSMETA1.cpg"                           
## [21] "MUNICIPIOSMETA1.dbf"                           
## [22] "MUNICIPIOSMETA1.prj"                           
## [23] "MUNICIPIOSMETA1.qmd"                           
## [24] "MUNICIPIOSMETA1.shp"                           
## [25] "MUNICIPIOSMETA1.shx"                           
## [26] "rsconnect"
(Platanos = read_csv("C:\\Users\\PERSONAL\\Documents\\cuaderno1y2\\meta_Platanos_2020.csv",show_col_types = FALSE))
## New names:
## * `` -> ...1
(mun.tmp =  st_read("C:\\Users\\PERSONAL\\Documents\\cuaderno1y2\\MUNICIPIOSMETA1.shp"))
## Reading layer `MUNICIPIOSMETA1' from data source 
##   `C:\Users\PERSONAL\Documents\cuaderno1y2\MUNICIPIOSMETA1.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 29 features and 11 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -74.89921 ymin: 1.604238 xmax: -71.07753 ymax: 4.899101
## CRS:           NA
mun.tmp %>% select(MPIO_NAREA,MPIO_CCNCT,) -> municipios
municipios
(cities = read_csv("C:\\Users\\PERSONAL\\Documents\\cuaderno1y2\\co.csv"))
## Rows: 1102 Columns: 9
## -- Column specification --------------------------------------------------------
## Delimiter: ","
## chr (5): city, country, iso2, admin_name, capital
## dbl (4): lat, lng, population, population_proper
## 
## i Use `spec()` to retrieve the full column specification for this data.
## i Specify the column types or set `show_col_types = FALSE` to quiet this message.
sf.cities <-  st_as_sf(x =cities,
                        coords = c("lng", "lat"))
sf.cities
st_crs(sf.cities) <- 4326
st_crs(municipios) <- 4326
st_crs(sf.cities)
## Coordinate Reference System:
##   User input: EPSG:4326 
##   wkt:
## GEOGCRS["WGS 84",
##     DATUM["World Geodetic System 1984",
##         ELLIPSOID["WGS 84",6378137,298.257223563,
##             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["World."],
##         BBOX[-90,-180,90,180]],
##     ID["EPSG",4326]]
st_crs(municipios)
## Coordinate Reference System:
##   User input: EPSG:4326 
##   wkt:
## GEOGCRS["WGS 84",
##     DATUM["World Geodetic System 1984",
##         ELLIPSOID["WGS 84",6378137,298.257223563,
##             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["World."],
##         BBOX[-90,-180,90,180]],
##     ID["EPSG",4326]]

####.4 limpiamos los datos con datos relevantes de nuestro departamento.

sf.cities.joined <- st_join(sf.cities, municipios, join = st_within)
sf.cities.joined
meta.cities = dplyr::filter(sf.cities.joined, admin_name=='Meta')
meta.cities 

######5.el primer cultivo de mayo importancia en el departamento del meta.

library(tmap)
library(ggplot2)
library(ggrepel)
library(classInt)
class(Platanos$Cod_Mun)
## [1] "numeric"
class(municipios$MPIO_CCNCT)
## [1] "character"
municipios$MPIO_CCNCT = as.numeric(municipios$MPIO_CCNCT)
munic_Platanos = left_join(municipios,Platanos, by = c( "MPIO_CCNCT"="Cod_Mun"))
munic_Platanos
breaks <- classIntervals(na.omit(munic_Platanos$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_Platanos <-  munic_Platanos %>%
  mutate(faktor_class = factor(cut(max_prod, breaks$brks, include.lowest = T), labels = lab_vec))
munic_Platanos$Produccion = munic_Platanos$faktor_class
munic_Platanos$mid <- sf::st_centroid(munic_Platanos$geometry)
munic_Platanos
LONG = st_coordinates( munic_Platanos$mid)[,1]
LAT = st_coordinates(munic_Platanos$mid)[,2]
ggplot(data = munic_Platanos) +
   geom_sf(aes(fill = Produccion)) +
   geom_label_repel(aes(x = LONG, y = LAT, label = MPIO_CCNCT), 
                    label.padding = unit(0.05,"lines"),  
                    label.r = unit(0.025, "lines"),
                    label.size = 0.05)

######6.representamos el segundo cultivo de mayor importancia en el departamento del meta.

(cereales = read_csv("C:\\Users\\PERSONAL\\Documents\\cuaderno1y2\\meta_Cereales_2020.csv",show_col_types = FALSE))
## New names:
## * `` -> ...1
cereales$Cod_Mun = as.character(cereales$Cod_Mun)
municipios$MPIO_CCNCT = as.character(municipios$MPIO_CCNCT)
munic_cereales = left_join(municipios, cereales, by = c("MPIO_CCNCT" = "Cod_Mun"))
munic_cereales
facet = "max_prod"
cereales_map =  
  tm_shape(munic_cereales) + tm_polygons(facet) + tm_text(text = "MPIO_CCNCT", size = 0.7, fontfamily = "sans") +
  tm_shape(meta.cities) + 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 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
cereales_map
## Credits not supported in view mode.
## Symbol shapes other than circles or icons are not supported in view mode.

https://rpubs.com/gundap0411/892320

sessionInfo()
## R version 4.1.3 (2022-03-10)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 8.1 x64 (build 9600)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=Spanish_Colombia.1252  LC_CTYPE=Spanish_Colombia.1252   
## [3] LC_MONETARY=Spanish_Colombia.1252 LC_NUMERIC=C                     
## [5] LC_TIME=Spanish_Colombia.1252    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] classInt_0.4-3 ggrepel_0.9.1  ggplot2_3.3.5  tmap_3.3-3     sf_1.0-7      
## [6] s2_1.0.7       dplyr_1.0.8    readr_2.1.2    readxl_1.3.1  
## 
## loaded via a namespace (and not attached):
##  [1] sass_0.4.1              bit64_4.0.5             vroom_1.5.7            
##  [4] jsonlite_1.8.0          viridisLite_0.4.0       bslib_0.3.1            
##  [7] assertthat_0.2.1        highr_0.9               sp_1.4-6               
## [10] cellranger_1.1.0        yaml_2.3.5              pillar_1.7.0           
## [13] lattice_0.20-45         glue_1.6.2              digest_0.6.29          
## [16] RColorBrewer_1.1-2      leaflet.providers_1.9.0 colorspace_2.0-3       
## [19] htmltools_0.5.2         XML_3.99-0.9            pkgconfig_2.0.3        
## [22] raster_3.5-15           stars_0.5-5             purrr_0.3.4            
## [25] scales_1.1.1            terra_1.5-21            tzdb_0.2.0             
## [28] tibble_3.1.6            proxy_0.4-26            farver_2.1.0           
## [31] generics_0.1.2          ellipsis_0.3.2          withr_2.5.0            
## [34] leafsync_0.1.0          cli_3.2.0               mime_0.12              
## [37] magrittr_2.0.2          crayon_1.5.1            evaluate_0.15          
## [40] fansi_1.0.2             lwgeom_0.2-8            class_7.3-20           
## [43] tools_4.1.3             hms_1.1.1               lifecycle_1.0.1        
## [46] stringr_1.4.0           munsell_0.5.0           compiler_4.1.3         
## [49] jquerylib_0.1.4         e1071_1.7-9             rlang_1.0.2            
## [52] units_0.8-0             grid_4.1.3              tmaptools_3.1-1        
## [55] dichromat_2.0-0         rstudioapi_0.13         htmlwidgets_1.5.4      
## [58] crosstalk_1.2.0         leafem_0.2.0            base64enc_0.1-3        
## [61] rmarkdown_2.13          wk_0.6.0                gtable_0.3.0           
## [64] codetools_0.2-18        abind_1.4-5             DBI_1.1.2              
## [67] markdown_1.1            R6_2.5.1                knitr_1.38             
## [70] fastmap_1.1.0           bit_4.0.4               utf8_1.2.2             
## [73] KernSmooth_2.23-20      stringi_1.7.6           parallel_4.1.3         
## [76] Rcpp_1.0.8.3            vctrs_0.3.8             png_0.1-7              
## [79] leaflet_2.1.1           tidyselect_1.1.2        xfun_0.30