Wednesday, February 19, 2020

R cartogram and WDI

#cartogramEx.R
#wdi and cartogram
#https://trucvietle.me/r/tutorial/2016/12/18/cartogram-plotting-using-r.html

setwd('~/Downloads')  #shapefile is here, fetched from thematic mapping org
library(Rcartogram)
library(getcartr)
library(ggplot2)
require(WDI)  #PREV: install.packages(c('RJSONIO', 'wdi'))
WDIsearch('gdp.*capita.*constant')
dat = WDI(indicator='NY.GDP.PCAP.KD', start=2012, end=2012, extra=TRUE)  #include aggregates ie continents
datsmall <- data.frame(iso3 = dat$iso3c, persoinc = dat$NY.GDP.PCAP.KD)
datsmall <- na.omit(datsmall)

world <- readShapePoly('TM_WORLD_BORDERS-0.3.shp')

## Join the two datasets using their common field
matchIds <- match(world@data[, "ISO3"], datsmall[, "iso3"])
world@data <- data.frame(world@data, datsmall[matchIds, ])
worldCarto <- quick.carto(world, world@data$persoinc, blur = 0.5)

## Convert the object into data frame
world.f <- fortify(worldCarto, region = "iso3")
## Merge the cartogram transformation with the world map shapefile
world.f <- merge(world.f, world@data, by.x = "id", by.y = "iso3")
my_map <- ggplot(world.f, aes(long, lat, group = group, fill = world.f$persoinc)) +
  geom_polygon() + theme_void() + scale_fill_continuous(name="Average\nIncome") ##ODD WAY to name legend

(my_map <- my_map + ggtitle("Cartogram of average income (2012)"))

0 Comments:

Post a Comment

<< Home