Skip to content

Instantly share code, notes, and snippets.

@ramnathv
Created March 9, 2011 22:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramnathv/863171 to your computer and use it in GitHub Desktop.
Save ramnathv/863171 to your computer and use it in GitHub Desktop.
# FUNCTION TO CREATE A CHOROPLETH MAP USING SPPLOT
choropleth_sp <- function(.poly, id1, .df = .poly@data, id2 = id1, field,
.title = "", .legtitle = "Values", colpal = 'PuRd', ...){
# load required libraries
library(maptools); library(spatial); library(RColorBrewer);
library(classInt); library(ggplot2); gpclibPermit();
# create id to match shapefile with data
id1 = llply(id1, as.name);
id2 = llply(id2, as.name);
.poly@data$id = with(.poly@data, do.call('paste', c(id1, sep = "-")));
.df$id = with(.df, do.call('paste', c(id2, sep = "-")));
# merge with data
map.data = merge(.poly@data, .df);
# choose breaks and fill colours
map.data.m = melt(map.data, measure.vars = field);
breaks = do.call("classIntervals", list(var = map.data.m$value, ...))$brks;
# map.data = within(map.data, {value = cut(value, breaks, incl = T)});
# plot choropleth map
# map.data = data.frame(cast(map.data, id ~ variable));
colors = brewer.pal(length(breaks) - 1, colpal);
.poly@data = map.data[match(.poly@data$id, map.data$id),];
p1 = spplot(.poly, field, at = breaks, col.regions = colors, col = 'transparent',
main = .title);
return(p1)
}
# FUNCTION TO READ SHAPE FILE FROM A ZIPPED FOLDER
readShapeZip <- function(url, .tempfile = tempfile(),
.tempdir = tempdir()){
require(maptools); gpclibPermit();
download.file(url = url, .tempfile, quiet = T);
.files = unzip(.tempfile, exdir = .tempdir);
.shpfile = head(.files)[grep('shp', head(.files))];
.poly = readShapeSpatial(.shpfile);
return(.poly)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment