Skip to content

Instantly share code, notes, and snippets.

@puncoz
Forked from anjesh/map.choropleth.nepal-updated.R
Created April 30, 2017 13:59
Show Gist options
  • Save puncoz/6687072ec9ea06ac1b91ad21a596fbe6 to your computer and use it in GitHub Desktop.
Save puncoz/6687072ec9ea06ac1b91ad21a596fbe6 to your computer and use it in GitHub Desktop.
Step-by-step plotting choropleth map of Nepal
library(rgdal)
library(ggplot2)
library(dplyr)
# clone NepalMaps from https://github.com/anjesh/NepalMaps
# read shapefile
nepal.adm3.shp <- readOGR(dsn="./NepalMaps/baselayers/NPL_adm", layer="NPL_adm3", stringsAsFactors = FALSE)
# fortify shapefile data to data frame
nepal.adm3.shp.df <- fortify(nepal.adm3.shp, region = "NAME_3")
# write districts to csv file
nepal.adm3.shp.df %>%
distinct(id) %>%
write.csv("districts.csv", row.names = FALSE)
# update the HPI data in districts.csv as per http://data.opennepal.net/content/human-poverty-index-value-districts-2011
hpi.data <- read.csv("districts.csv")
colnames(hpi.data) <- c("id","HPI")
# merge hpi data with shapefile dataframe
nepal.adm3.shp.df <- merge(nepal.adm3.shp.df, hpi.data, by ="id")
# finding the centers of all the district polygons. Thanks http://stackoverflow.com/questions/28962453/how-can-i-add-labels-to-a-choropleth-map-created-using-ggplot2
centroids <- setNames(do.call("rbind.data.frame", by(nepal.adm3.shp.df, nepal.adm3.shp.df$group, function(x) {Polygon(x[c('long', 'lat')])@labpt})), c('long', 'lat'))
centroids$label <- nepal.adm3.shp.df$id[match(rownames(centroids), nepal.adm3.shp.df$group)]
# showing district names for which HPI>40
centroids.selected <- centroids[centroids$label %in% (hpi.data[hpi.data$HPI>40,]$id),]
# setting up bare theme
theme_bare <- theme(
axis.line = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
legend.text=element_text(size=7),
legend.title=element_text(size=8),
panel.background = element_blank(),
panel.border = element_rect(colour = "gray", fill=NA, size=0.5)
)
# plot map
ggplot(data = nepal.adm3.shp.df,aes(x = long, y = lat, group = group)) +
geom_polygon(aes(fill = HPI), color = 'gray', size = 0.1) +
ggtitle("Human Poverty Index Map") +
guides(fill=guide_colorbar(title="HP Index")) +
scale_fill_gradient(high = "#e34a33", low = "#fee8c8", guide = "colorbar") +
coord_fixed(1.3) +
theme(legend.justification=c(0,-0.1), legend.position=c(0.05,0)) +
with(centroids.selected, annotate(geom="text", x = long, y = lat, label=label, size=2)) +
theme_bare
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment