Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Choropleth Maps are very useful to visualize spatial trends. There have been several blog posts providing detailed instructions on how to create a choropleth map in R using map, spplot and ggplot2. However, I believe that the process of creating a choropleth should be even simpler given the power of R. Hence I set out to create a generic function to plot choropleths.
I think it would be useful to share my design principles before I step on to my code. In my mind, it should be possible to quickly draw a choropleth map by specifying the following inputs:
- poly => shapefile containing the map
- df => data file containing the info
- id1, id2 => names to merge poly and df
- field => value variables to plot
- colpal => color palette
- … => inputs to create data bins
Example 1
Let us consider a simple example to illustrate this principle. I am going to use a recent choropleth map created in the Offensive Politics blog to visualize the percentage of votes secured by the winning candiate Rahm Emanuel in the Chicago Mayoral Elections.
The plotChoropleth function essentially takes the grunt work out of constructing a choropleth map once the data has been loaded and cleaned, and produces the plot shown below.
Example 2
Suppose, we want to visualize vote pcts of both Rahm Emanuel and Gery Chico. The plotChoropleth function automatically creates facets when it is provided more than one field variable to plot.
Example 3
The flexibility does not end here. Let us suppose, we want to visualize the pct of votes secured by the winner of each precinct. Such a plot was created by the Chicago Tribune . In this plot the palette used for each candidate is different. We can create this plot, by additional processing on the election results data, and directly passing the fill color for each precinct to the plotChoropleth function. This produces the plot on top of this page after a few extra lines of code to set the legend right.
https://gist.github.com/856685
Example 4
Finally, in some cases, the shape file already has the data to be plotted. Let me illustrate this case with an example on London Sport Participation drawn from the Spatial Analysis blog. When a data file is not specified, the plotChoropleth function assumes that it is contained in the shape file and proceeds with it as default.
https://gist.github.com/856695
I am in the process of cleaning up my code and putting them on github as a downloadable repository. I would be glad to get feedback and comments on how I can improve this further.
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.