Skip to content

Instantly share code, notes, and snippets.

@mbacou
Last active October 28, 2015 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbacou/69d192276be2ba5e666d to your computer and use it in GitHub Desktop.
Save mbacou/69d192276be2ba5e666d to your computer and use it in GitHub Desktop.
#####################################################################################
# Title: Nigeria Urban Mask
# Date: Sep 2015
# Project: HarvestChoice
# Author: Bacou, Melanie <mel@mbacou.com>
#####################################################################################
library(raster)
library(tmap)
setwd("~/Projects/hc-cell5m")
# Load Landscan 2012 raster
pop <- raster("../../Maps/LandScan_2012/lspop2012/w001001.adf")
# Load GAUL 2008
load("./rdb/g0.rda")
# Keep only Nigeria
nga <- g0[g0$ADM0_NAME=="Nigeria",]
rm(g0)
# Transform `nga` to match the projection of the raster
nga <- spTransform(nga, proj4string(pop))
# Crop and mask all values outside NGA
pop.nga <- mask(crop(pop, nga), nga)
# Verify min, max, and total
cellStats(pop.nga, "min")
# [1] 0
cellStats(pop.nga, "max")
# [1] 80301
cellStats(pop.nga, "sum")
# [1] 170038988
# At what cutoff value (pixel density) the cumulative sum of pixel values reaches 48%?
totpop <- cellStats(pop.nga, "sum")
rural.rate <- .48
# Find cutoff
pop.dt <- as.vector(pop.nga)
pop.dt <- sort(pop.dt)
cutoff <- pop.dt[cumsum(pop.dt) >= totpop*rural.rate][1]
cutoff
# [1] 1363
# Plot this
y <- unique(pop.dt)
y <- sapply(y, function(x) sum(pop.dt[pop.dt<=x]))
plot(x=unique(pop.dt), y=100*y/totpop, xlim=c(0,3000),
xlab="pixel density", ylab="percent of total population")
abline(h=100*rural.rate, col="red", lty=4)
abline(v=cutoff, col="red", lty=4)
# Verify
fun <- function(x) ifelse(x<=cutoff, x, 0)
pop.rurc <- calc(pop.nga, fun=fun)
cellStats(pop.rurc, "sum")/totpop
# [1] 0.4800308
# Classify 0-rural/1-urban areas using cutoff value
m <- c(0, cutoff, 0, cutoff, max(pop.dt)+1, 1)
m <- matrix(m, ncol=3, byrow=T)
pop.rur <- reclassify(pop.nga, m, include.lowest=T)
# Add levels
rat <- data.frame(ID=0:1, levels=c("rural", "urban"))
levels(pop.rur) <- rat
# Plot results
tm_shape(pop.rur) +
tm_raster("layer", style="fixed", breaks=c(0,1),
legend.hist=T, legend.hist.z=0, title="Urban Population") +
tm_layout(inner.margins=c(0,0.35,0,0))
@mbacou
Copy link
Author

mbacou commented Sep 19, 2015

pop2012_01

pop2012_02

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment