Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting color map with zip codes in R or Python

I have some US demographic and firmographic data.
I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to http://maps.huge.info/ but a) with annotated text; b) pdf output; c) scriptable in R or Python.

Is there any package and code that allows me to do this?

like image 954
gappy Avatar asked Sep 17 '09 22:09

gappy


2 Answers

I am assuming you want static maps.

alt text
(source: eduardoleoni.com)

1) Get the shapefiles of the zip boundaries and state boundaries at census.gov:

2) Use the plot.heat function I posted in this SO question.

For example (assumes you have the maryland shapefiles in the map subdirectory):

library(maptools) ##substitute your shapefiles here state.map <- readShapeSpatial("maps/st24_d00.shp") zip.map <- readShapeSpatial("maps/zt24_d00.shp") ## this is the variable we will be plotting zip.map@data$noise <- rnorm(nrow(zip.map@data)) ## put the lab point x y locations of the zip codes in the data frame for easy retrieval labelpos <- data.frame(do.call(rbind, lapply(zip.map@polygons, function(x) x@labpt))) names(labelpos) <- c("x","y")                         zip.map@data <- data.frame(zip.map@data, labelpos) ## plot it png(file="map.png") ## plot colors plot.heat(zip.map,state.map,z="noise",breaks=c(-Inf,-2,-1,0,1,2,Inf)) ## plot text with(zip.map@data[sample(1:nrow(zip.map@data), 10),] , text(x,y,NAME)) dev.off() 
like image 116
Eduardo Leoni Avatar answered Sep 22 '22 17:09

Eduardo Leoni


There are many ways to do this in R (see the spatial view); many of these depend on the "maps" package.

  • Check out this cool example of the US 2004 election. It ends up looking like this:alt text

  • Here's a slightly ugly example of a model that uses the "maps" package with "lattice".

  • Andrew Gelman made some very nice plots like this. See, for instance, this blog post on red states/blue states and this follow up post.
  • Here's a very simple example using the "gmaps" package, which shows a map of Arrests by state for arrests per 100,000 for Murder:

    require(gmaps) data(USArrests) attach(USArrests) grid.newpage() grid.frame(name="map") grid.pack("map",USALevelPlot(states=rownames(USArrests),levels=Murder,col.fun=reds),height=unit(1,'null')) grid.pack("map",gradientLegendGrob(at=quantile(Murder),col.fun=reds),side="bottom",height=unit(.2,'npc')) detach(USArrests) 
like image 32
Shane Avatar answered Sep 22 '22 17:09

Shane