library(cartogram)
library(sf)
## Linking to GEOS 3.9.1, GDAL 3.4.3, PROJ 7.2.1; sf_use_s2() is TRUE
library(readxl)
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(ggplot2)
library(tmap)
library(tidyr)
setwd("C:/Users/User/Desktop/MAPA")
mundo <- st_read("countries.geo.json")
## Reading layer `countries.geo' from data source 
##   `C:\Users\User\Desktop\MAPA\countries.geo.json' using driver `GeoJSON'
## Simple feature collection with 180 features and 2 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -180 ymin: -85.60904 xmax: 180 ymax: 83.64513
## Geodetic CRS:  WGS 84
setwd("C:/Users/User/Desktop/DATA")
sdg <- read_excel("SDGDATA.xlsx")
plot(mundo$geometry)

mundo3857 <- st_transform(mundo, 3857)
plot(mundo3857$geometry, main = "Mapa del mundo (EPSG:3857")

#Eliminamos Antartida

mundo3857 <- mundo3857 %>%
  filter(!name %in% 'Antarctica')

#Merge

mundo_sdg <- left_join(mundo3857, sdg, by=c('name'='Country'))
mundo_sdg_noNA <- mundo_sdg %>% replace_na(list(SDGIndex = 0.1))

#Cartogram

sdg_cartogram <- cartogram_cont(mundo_sdg_noNA, "SDGIndex", itermax = 8)
## Mean size error for iteration 1: 21.5884163796246
## Mean size error for iteration 2: 15.1852359694619
## Mean size error for iteration 3: 10.9858959413558
## Mean size error for iteration 4: 8.29026820387405
## Mean size error for iteration 5: 6.68282935789965
## Mean size error for iteration 6: 5.55832532129011
## Mean size error for iteration 7: 4.83607159281229
## Mean size error for iteration 8: 4.33116717209753
dtemp<-replace(sdg_cartogram$SDGIndex, sdg_cartogram$SDGIndex == 0.1, 0)
mapa_final <- sdg_cartogram %>% mutate(SDGIndex = dtemp)
tm_shape(mapa_final) +
  tm_style("gray") +
  tm_layout(main.title = "Desarrollo sostenible por país, según ODS",
            main.title.size = 1,
            title = "Fuente: Sustainable Development Report, UNSDSN (2022)", title.size = 0.45)+
  tm_polygons(col = "SDGIndex", style = "cont",
              breaks= c(0,30, 60, 90), palette = "Blues",
              title = "SDG") +
  tm_scale_bar(position = c("left", "bottom"), width = 0.1) +
  tm_compass(position = c("0.001", "0.09"), size = 1.5)+
  tm_credits("Grupo 2 - Teorías del Desarrollo, 2022")