**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:

- Scrape Wikipedia for election results (as seen here before)
- Load a state shapefile (as we’ve done previously)
- 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.
- 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.

**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...