# Dot-density maps with spsample()

**is.R()**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 their blog:

**is.R()**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.