County-Level Choropleth in Plotly and R

At Plotly, we are commonly asked about thematic maps — especially county-level choropleth maps. This style of map provides a visual illustration of variation across a geographic area. Some pertinent uses are population density, economic measurements, crime statistics, and election results. With Plotly, there are multiple ways to bring county-level choropleths to life. For example,

using ggplotly

or native plot_ly

or plot_mapbox

. . .

For now, we will look at how to create the US electoral map using the ggplotly method. For more information concerning the plot_ly and plot_mapbox examples, checkout our R documentation library.

 . . .

Before we get started, we have to retrieve the data. The 2016 US election data can be sourced from Kaggle. For the map data, county and state boundaries, we can us the Maps package via ggplot2, which is loaded with Plotly package. Thus, we can load the Plotly library and read in the election and map data. Additionally, we will make use of the dplyr package.

As we are using multiple datasets, we will need to ensure that county names match so that we are able to plot all the counties, parishes, etc.. Thus, we make sure county names are lower case and use gsub to remove any unnecessary words (such as “county” or “parish”) and characters. We do this to both datasets.

Next, we want to correct the vote measurement and then determine who won which county by checking which candidate had the greater amount of votes.

Rename for consistency, then join the two datasets using dplyr and remove any duplicates.

. . .

As previously illustrated, there are multiple ways to visualize county-level choropleths in Plotly but we will focus on using ggplot2 and converting it to a Plotly object with ggplotly. Here, call ggplot using longitude, latitude, and group, and geom_polygon to color counties by the winning candidate. Additionally, we utilize a third dataset (state boundaries) in the second geom_polygon to add a familiar shape to our map. Finally, remove the axes, grid lines, and background to set the theme.

. . .

Now using the magic of ggplotly, we can convert this static plot into an interactive Plotly object. Furthermore, we have the option of extending the Plotly object by adding layout attributes and, or, modifying existing, or default, attributes by utilizing the style function.

Once you’re happy with the final product, and have added your Plotly credentials, you can publish it to your Plotly account.

. . .

Want More?

If you like this, checkout the full code here and more examples via our R documentation library.

If you’re looking for something more in-depth, then consider attending the 2 day R/Shiny Master Class in NYC November 18–19, where you’ll cover topics such as extending ggplot2, animations, linked brushing, and Shiny, whilst learning to build “stats apps” that have rich and interactive controls.