<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/county-level-choropleth-in-plotly-and-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://moderndata.plot.ly/county-level-choropleth-in-plotly-and-r/"> R – Modern Data</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>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,</p>
<p>using <em>ggplotly</em></p>
<p><iframe width="450" src="https://plot.ly/~bdun9/2239.embed"></iframe></p>
<p>or native <em>plot_ly</em></p>
<p><iframe width="450" src="https://plot.ly/~bdun9/2258.embed"></iframe></p>
<p>or <em>plot_mapbox</em></p>
<p><iframe width="450" src="https://plot.ly/~bdun9/2196.embed"></iframe></p>
<p><strong>. . .</strong></p>
<p>For now, we will look at how to create the US electoral map using the <em>ggplotly</em> method. For more information concerning the <em>plot_ly</em> and <em>plot_mapbox</em> examples, checkout our <a rel="nofollow" href="https://plot.ly/r/" data-href="https://plot.ly/r/" target="_blank">R documentation library</a>.</p>
<p><strong> . . .</strong></p>
<p>Before we get started, we have to retrieve the data. The 2016 US election data can be sourced from <a rel="nofollow" href="https://www.kaggle.com/joelwilson/2012-2016-presidential-elections/data" data-href="https://www.kaggle.com/joelwilson/2012-2016-presidential-elections/data" target="_blank">Kaggle</a>. 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.</p>

<pre>#install.packages(“plotly”)

library(plotly)
library(dplyr)

county_df &lt;- map_data(&quot;county&quot;)
state_df &lt;- map_data(&quot;state&quot;)

df &lt;- read.csv(&quot;https://raw.githubusercontent.com/bcdunbar/datasets/master/votes.csv&quot;)</pre>

<p>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 <em>gsub</em> to remove any unnecessary words (such as “county” or “parish”) and characters. We do this to both datasets.</p>

<pre>df &lt;- subset(df, select = c(Clinton, Trump, county_name))

df$county_name %&lt;>%
  gsub(&quot; county&quot;, &quot;&quot;, .) %>%
  gsub(&quot; parish&quot;, &quot;&quot;, .) %>%
  gsub(&quot; &quot;, &quot;&quot;, .) %>%
  gsub(&quot;[.]&quot;, &quot;&quot;, .)

county_df$subregion &lt;- gsub(&quot; &quot;, &quot;&quot;, county_df$subregion)</pre>

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

<pre>df$Clinton &lt;- df$Clinton*100
df$Trump &lt;- df$Trump*100

for (i in 1:length(df[,1])) {
  if (df$Clinton[i] > df$Trump[i]) {
    df$win[i] = 'Clinton'
  } else {
    df$win[i] = 'Trump'
  }
}</pre>

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

<pre>names(df) &lt;- c(&quot;clinton&quot;, &quot;trump&quot;, &quot;subregion&quot;, &quot;win&quot;)

choropleth &lt;- inner_join(county_df, df, by = &quot;subregion&quot;)
choropleth &lt;- choropleth[!duplicated(choropleth$order), ]</pre>

<p><strong>. . .</strong></p>
<p>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.</p>

<pre>p &lt;- ggplot(choropleth, aes(long, lat, group = group)) +
  geom_polygon(aes(fill = win), 
               colour = alpha(&quot;white&quot;, 1/2), size = 0.1)  +
  geom_polygon(data = state_df, colour = &quot;white&quot;, fill = NA) + 
  scale_fill_manual(values = c('blue','red')) +
  theme_void()</pre>

<p><strong>. . .</strong></p>
<p>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.</p>

<pre>p &lt;- ggplotly(p, tooltip = 'text') %>% 
  layout(
    hovermode = 'x',
    margin = list(
      t = 20,
      b = 20,
      l = 20,
      r = 20),
    legend = list(
      orientation = 'h',
      x = 0.5,
      y = 1.01,
      xanchor = 'center'))

# use style to modify layer
p &lt;- style(p, hoverinfo = 'none', traces = c(3))

# use plotly_build to modify layer
p &lt;- plotly_build(p)
str(p$x$layout$annotations) # check annotations
p$x$layout$annotations = NULL # remove annotation</pre>

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

<pre>Sys.setenv(&quot;plotly_username&quot; = &quot; ... &quot;)
Sys.setenv(&quot;plotly_api_key&quot; = &quot; ... &quot;)

api_create(p, filename = 'US 2016 Election')</pre>

<p><strong>. . .</strong></p>
<p><strong>Want More?</strong></p>
<p>If you like this, checkout the full code <a rel="nofollow" href="https://plot.ly/~bdun9/2242" target="_blank">here</a> and more examples via our <a rel="nofollow" href="https://plot.ly/r/" data-href="https://plot.ly/r/" target="_blank">R documentation library</a>.</p>
<p>If you’re looking for something more in-depth, then consider attending the 2 day <a rel="nofollow" href="https://plotcon.plot.ly/workshops" data-href="https://plotcon.plot.ly/workshops" target="_blank"><strong>R/Shiny Master Class</strong></a> 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.</p>
<p> </p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://moderndata.plot.ly/county-level-choropleth-in-plotly-and-r/"> R – Modern Data</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/ZSZiSPdiyVo" height="1"></a></div>