jalan-jalan sambil minum teh-tarek

Friday, July 28, 2017

choropleth map and cartogram

#map-dementia.R
#prevalence preserving map of dementia in England
#GT 12 Jan 2016, 28 July 2017

#install.packages('Rcartogram', repos='http://www.omegahat.org/R', type='source')
#actually: stackoverflow.com/questions/31613119/installing-rcartogram-packages-error-message
library(fftw)
library(Rcartogram)
#install_github('chrisbrunsdon/getcartr',subdir='getcartr')
#install.packages('devtools') #bits may need to be installed in piecemeal
#library(devtools)
library(getcartr)
library(rgdal)
library(ggplot2)
library(ggmap)
library(mapproj)
library(Cairo)
library(foreign)
library(scales)
library(dplyr)
library(plyr)

#setwd('C:/data/dementia')
setwd('C:/_projects/dementia')
dir()
dir('England_lad_shp_2011')

#choro
engY <- read.dta('w7ticsLA.dta') #OSLAUA2 is chr
engY$OSLAUA2 <- as.factor(engY$OSLAUA2)
engY <- rename(engY, c("tics27demen"="Dementia"))
names(engY)
summary(engY$Dementia)  #min 0, max 19.0%

engshp <- readShapePoly('England_lad_shp_2011/england_lad_2011_gen_clipped') #readOGR failed.
names(engshp) #altname name code: all factors
engshp <- fortify(engshp, region="code") # code -> id
eng2 <- merge(engshp, engY, by.x="id", by.y="OSLAUA2")

chorodem <- ggplot() +
  geom_polygon(data = eng2, aes(long, lat, group=group, fill=Dementia)) +
  scale_fill_distiller(palette = "Reds", trans = "reverse", labels = percent, breaks = pretty_breaks(n=5)) +
  guides(fill = guide_legend(reverse = TRUE)) +
  theme_nothing(legend = TRUE)
chorodem
ggsave(chorodem, file = "dementiachoro.png", width = 5.5, height = 7, type = "cairo-png")

#carto
engY <- read.dta('w7ticsLA.dta') #OSLAUA2 is chr
engY$OSLAUA2 <- as.factor(engY$OSLAUA2)
engY <- rename(engY, c("tics27demen"="Dementia"))
names(engY)

engshp <- readShapePoly('England_lad_shp_2011/england_lad_2011_gen_clipped') #reread
match.indices <- match(engshp@data[, "code"], engY[, "OSLAUA2"])
engshp@data <- data.frame(engshp@data, engY[match.indices, ])

engshp.carto <- quick.carto(engshp, engshp@data$Dementia, blur=0)  # minutes later...
engshp.buffer <- gBuffer(engshp.carto, width=0, byid=TRUE)
engshp.f <- fortify(engshp.buffer, region="OSLAUA2")  #ONS_LABEL -> id
engshp.f <- merge(engshp.f, engshp@data, by.x="id", by.y="OSLAUA2") #merge carto with map

#england.f$qimd <- england.f$qimd/100
cartodem <- ggplot() +
  geom_polygon(data = engshp.f, aes(long, lat, group=group, fill=Dementia)) +
  scale_fill_distiller(palette = "Reds", trans = "reverse", labels = percent, breaks = pretty_breaks(n=5)) +
  guides(fill = guide_legend(reverse = TRUE)) +
  theme_nothing(legend = TRUE)
cartodem
ggsave(cartodem, file = "dementiacarto.png", width = 5.5, height = 7, type = "cairo-png")