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