Dot-density maps with spsample()

December 7, 2012
By

(This article was first published on is.R(), and kindly contributed to R-bloggers)

Today’s example is a little odd, in that the code isn’t pretty and the example isn’t really something you’d actually produce in real life — but if you’ll overlook those oddities, you’ll find that the spsample() function, and the sp package generally, can be very useful.

One of the problems with choropleth maps is the degree to which geographic areas can distort viewer perceptions of the distribution of the color-mapped variable. A good treatment of this problem can be found here, and cartograms are a typical solution. It is possible to retain the original map projection shape, but convey density with transparency or dot-density, and the latter is what today’s Gist illustrates.

Now, the odd thing about this particular example is that I illustrate the dot-density approach using state-level data — and it really doesn’t work as well as county-level data would. When county-level returns become available in a convenient format (let us know if you have it!), I’ll update this map. Until then, the principles are the same regardless of the shapefile you use.

This script goes through a couple of different steps:

  1. Scrape Wikipedia for election results (as seen here before)
  2. Load a state shapefile (as we’ve done previously)
  3. With a loop, convert each state shape to a SpatialPolygons object, and randomly draw points from within each state polygon to represent Democratic, Republican, and Other voters.
  4. Plot the map and these randomly drawn points, so that states with few votes appear very sparsely populated, while states with many votes appear densely populated. Coloring each point by candidate choice conveys the predominant leaning of each state.
As I mentioned, this would work better for counties, but in the meantime:

To leave a comment for the author, please follow the link and comment on his blog: is.R().

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.