Alex Rivera | Logout

Create a heatmap of USA with state abbreviations and characteristic frequency in R

Asked 2011-12-16T17:14:02.400
8

I would like to create a map of the USA (perhaps a heatmap) to show frequency of a certain characteristic among states. I am not sure of what package to use or if my data is in the proper form. My data is in the table tf

tf
 AB  AK  AL  AN  AR  AZ  CA  CO  CT  DC  DE  EN  FL  GA  HI  IA  ID  IL  IN  KS 
  1  21  31   1  12  56 316  53  31  16   7   1 335  63  11  42  29  73  40  2

For the most part, my abbreviations are US (aside from a few Canadian instances). What is the best suggested approach for graphically displaying this on a map?

Now how do I get granularity of less than 50 per color?

enter image description here

Edit
Report

1 Answer

8

Another approach with spplot:

library(maps)
library(maptools)
library(sp)

First read the data and add a column with the names of the states:

txt <- "AB  AK  AL  AN  AR  AZ  CA  CO  CT  DC  DE  EN  FL  GA  HI  IA  ID  IL  IN  KS
    1  21  31   1  12  56 316  53  31  16   7   1 335  63  11  42  29  73  40  2"

dat <- stack(read.table(text = txt,  header = TRUE))
names(dat)[2] <-'state.abb'
dat$states <- tolower(state.name[match(dat$state.abb,  state.abb)])

Then you get the map and convert it to a SpatialPolygons:

mapUSA <- map('state',  fill = TRUE,  plot = FALSE)
nms <- sapply(strsplit(mapUSA$names,  ':'),  function(x)x[1])
USApolygons <- map2SpatialPolygons(mapUSA,  IDs = nms,  CRS('+proj=longlat'))

And now you add the information from your data:

idx <- match(unique(nms),  dat$states)
dat2 <- data.frame(value = dat$value[idx], state = unique(nms))
row.names(dat2) <- unique(nms)

USAsp <- SpatialPolygonsDataFrame(USApolygons,  data = dat2)

Finally you plot it:

spplot(USAsp['value'])

Added imageenter image description here

answered 2011-12-19T10:10:14.743

Your Answer