Saturday, April 13, 2013

RG#58:ploting heatmap in map using maps package (US map example)

library(maps)
#get a state boundry map
usmap <- map("state", plot = FALSE, fill = TRUE)
dataf <- data.frame (states = usmap$names, yvar = abs(rnorm(length(usmap$names), 50,22)))


# define colors
colors <- topo.colors (6)

# categorize in different class for yvar
 dataf$colorBuckets <- as.numeric(cut(dataf$yvar, c(0, 30, 50, 70, 90, 130)))

# corresponding legend text
 legdtxt <- c("<0%", "0-30%", "30-50%", "50-70%", "70-90%", ">90%")


# plot map
  map("state", col = colors[dataf$colorBuckets], fill = TRUE, lty = 1, lwd = 0.2,    projection="polyconic")
  legend("topright", legdtxt, horiz = FALSE, fill = colors)


 # county level example
 # getting data
  require(mapproj)
  data(unemp)
  data(county.fips)


  # define color buckets
  colors = heat.colors(6)
  unemp$colorB <- as.numeric(cut(unemp$unemp, c(0, 2, 4, 6, 8, 10, 100)))
  legdtext <- c("<2%", "2-4%", "4-6%", "6-8%", "8-10%", ">10%")
 
 colorsmatched <- unemp$colorB [match(county.fips$fips, unemp$fips)]

  # draw map
  map("county", col = colors[colorsmatched], fill = TRUE, resolution = 0,
    lty = 0, projection = "polyconic")
   
  map("state", col = "white", fill = FALSE, add = TRUE, lty = 1, lwd = 0.2,
    projection="polyconic")
   
  title("US unemployment by county in year 2009")
 legend("topright", legdtext, horiz = FALSE, fill = colors)



1 comment:

  1. I like the effect! Shouldn't the colors be reversed to portray the information more accurately. The areas of high unemployment should appear darkest.

    ReplyDelete

Note: Only a member of this blog may post a comment.