Today I will demonstrate how to map historic US Presidential Election results in R. If you want to skip ahead and play with a shiny app that lets you visualize this dataset, then click here.

The dataset we will use comes from wikipedia’s List of United States presidential election results by state and is packaged in the choroplethr package as df_president_ts:

library(choroplethr) library(choroplethrMaps) data(df_president_ts) ?df_president_ts df_president_ts[1:8, 1:4] region 1789 1792 1796 1 alabama NA NA NA 2 alaska NA NA NA 3 arizona NA NA NA 4 arkansas NA NA NA 5 california NA NA NA 6 colorado NA NA NA 7 connecticut GW GW F 8 delaware GW GW F

The first column is a state name; subsequent columns are years that had presidential elections. NA means that the state did not yet exist. Note that by default choroplethr renders NA values as black. Here “GW” means “George Washington” and “F” means “Federalist”. You can see the legend at both the wikipedia link above as well as the help for ?df_president_ts.

In order to map data with choroplethr your data needs a column named region and a column named value. Here we are given the region column but not the value column. We can create a value column like this:

df_president_ts$value = df_president_ts$"1789" state_choropleth(df_president_ts, title = "1789 Presidential Election Map")

I originally packaged up this dataset to demonstrate the animation functionality of choroplethr (see ?choroplethr_animate). But since I have recently been doing a lot of work with Shiny, I thought that it would be nice to create an app that lets users view all of these maps with a simple dropdown menu. You can see the running app here. The source code for the app is available here. Here is a screenshot of the running app:

From Around the Web

Alyssa Briggs Hislop did an interesting series of blog posts that use choroplethr to map the behavior of library patrons in America: