<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/how-to-map-public-debt-data-with-ggplot2/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.sharpsightlabs.com/blog/map-public-debt-ggplot2/"> r-bloggers | SHARP SIGHT</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><a rel="nofollow" href="http://www.sharpsightlabs.com/join-newsletter-get-crash-course/" target="_blank"><br>
<img sizes="(max-width: 600px) 100vw, 600px" src="https://i0.wp.com/www.sharpsightlabs.com/wp-content/uploads/2018/03/euro_debt_map_NOTITLE-600x492.png?w=450" alt="" class="wp-image-3410" data-recalc-dims="1">
<p></p></a>
<p>You’ve heard me say it a thousand times: to master data science, you need to practice.</p>
<p>You need to “practice small” by <a href="http://www.sharpsightlabs.com/blog/simple-practice-maps-tidyverse/">practicing individual techniques and functions</a>. But you also need to “practice big” by working on larger <a href="http://www.sharpsightlabs.com/blog/choose-project-practice-data-science/#">projects</a>.</p>
<p>To get some practice, my recommendation is to find reasonably sized datasets online and plot them. </p>
<p>Wikipedia is a nearly-endless source of good datasets. The great thing about Wikipedia is that many of the datasets are small and well contained. They are also fairly clean, with just enough messiness to make them a bit of a challenge.</p>
<p>As a quick example, this week, we’ll plot some economic data.</p>
<h1>Plotting public debt using <code>ggplot2</code></h1>
<p>Here, we’re going to scrape some data from Wikipedia and plot it using ggplot2. </p>
<p>It sounds easy enough, but make note of the complexity here. We’re actually using several dozen techniques in mildly complex ways to get this done.</p>
<p>If you’re a beginner, take a careful look at this. You need to break this down, identify the tools that are being used, and make sure that you know them. (Hint: 80% of this is <a href="http://www.sharpsightlabs.com/blog/data-analysis-example-r-supercars-part2/">ggplot2 and dplyr</a> … make sure you master them.)</p>
<p>If you’re at an intermediate level and you now most of the R data science toolkit, take a look at how everything is being put together. </p>
<p>Don’t just run the code. Study it. You’ll become a better data scientist by studying other people’s code.</p>
<pre class="wp-code-highlight">
#=============
# LOAD PACKGES
#=============

library(tidyverse)
library(rvest)
library(stringr)


#=============
# READ WEBPAGE
#=============
html.public_debt_by_country &lt;- read_html('https://en.wikipedia.org/wiki/List_of_countries_by_public_debt')


#==================
# SCRAPE TABLE DATA
#==================
df.public_debt_by_country &lt;- html.public_debt_by_country %>% 
  html_nodes('table') %>% 
  .[[1]] %>% 
  html_table()


#===============
# RENAME COLUMNS
#===============
names(df.public_debt_by_country)

colnames(df.public_debt_by_country) &lt;- c('country'
                                         ,'debt_as_pct_of_gdp'
                                         , 'measure_year'
                                         , 'gross_debt_as_pct_of_gdp_IMF'
                                         , 'net_debt_as_pct_of_gdp_IMF'
                                         , 'measure_year_IMF'
                                         , 'region'
                                         )


#========================================================
# DROP EXTRA COLUMNS
# - The Wikipedia table has a couple of different sources
#   for very similar data.
# - We will drop the IMF data
#========================================================

df.public_debt_by_country %>% 
  select(-gross_debt_as_pct_of_gdp_IMF
         , -net_debt_as_pct_of_gdp_IMF
         , -measure_year_IMF
         ) ->
  df.public_debt_by_country


#=====================================================
# REMOVE RECORD FOR 'World'
# - The original data has a summary record for 'World'
# - we will remove this
#=====================================================
df.public_debt_by_country &lt;- df.public_debt_by_country %>% filter(country != 'World')


#============================
# COERCE data.frame TO tibble
#============================
df.public_debt_by_country &lt;-  df.public_debt_by_country %>% as_tibble()


#=============
# GET MAP DATA
#=============
df.map &lt;- map_data('world')


# INSPECT map data
df.map %>% glimpse()
df.map %>% names()


# INSPECT debt data
df.public_debt_by_country %>% glimpse()


#=============================
# RENAME 'region' to 'country'
#=============================
df.map %>%
  rename(country = region) ->
  df.map


df.map %>% glimpse()


#===============================
# IDENTIFY JOIN MISMATCHES
# - we will use an anti-join to 
#   identify mis-matches between
#   the country variable on our 
#   two different datasets
#===============================
anti_join(df.public_debt_by_country
          ,df.map
          ,by = 'country'
          )


# country debt_as_pct_of_gdp measure_year
# 1                Antigua and Barbuda               89.0         2012
# 2                              Burma                 NA           NA
# 3         People's Republic of China               20.1         2016
# 4  Congo, Democratic Republic of the               18.2         2016
# 5             Congo, Republic of the               49.3         2016
# 6                      Cote d'Ivoire               50.9         2016
# 7                        Gambia, The                 NA           NA
# 8                          Gibraltar                7.5         2008
# 9                          Hong Kong               38.4         2016
# 10                      Korea, North                 NA           NA
# 11                      Korea, South               46.1         2016
# 12             Saint Kitts and Nevis               83.0         2013
# 13  Saint Vincent and the Grenadines               67.0         2013
# 14               Trinidad and Tobago               61.0         2016
# 15                            Tuvalu               41.1         2013
# 16                    United Kingdom               92.2         2016
# 17                     United States               73.8         2016
# 18                             World               64.0         2012


#============================================
# GET COUNTRY NAMES FROM df.map
# - these will be the new names that we will
#   use when we re-code the names in 
#   df.public_debt_by_country
#============================================
df.map %>% 
  group_by(country) %>% 
  summarise() %>% 
  print(n = Inf)


# RECODE
df.public_debt_by_country %>% 
  mutate(country = recode(country
             ,`Antigua and Barbuda` = 'Antigua'
             ,`Burma` = 'Myanmar'
             ,`People's Republic of China` = 'China'
             ,`Congo, Democratic Republic of the` = 'Democratic Republic of the Congo'
             ,`Congo, Republic of the` = 'Republic of Congo'
             ,`Cote d'Ivoire` = 'Ivory Coast'
             ,`Gambia, The` = 'Gambia'
             #,`Gibraltar` = ''
             #,`Hong Kong` = ''
             ,`Korea, North` = 'North Korea'
             ,`Korea, South` = 'South Korea'
             ,`Saint Kitts and Nevis` = 'Saint Kitts'
             ,`Saint Vincent and the Grenadines` = 'Saint Vincent'
             ,`Trinidad and Tobago` = 'Trinidad'
             #,`Tuvalu` = ''
             ,`United Kingdom` = 'UK'
             ,`United States` = 'USA'
        )
  ) ->
  df.public_debt_by_country


#===========================
# RE-INSPECT JOIN MISMATCHES
# note: these last 3 are OK
#===========================
anti_join(df.public_debt_by_country
          ,df.map
          ,by = 'country'
          )

#=====
# JOIN
#=====
df.map_public_debt &lt;- left_join(df.map
                                ,df.public_debt_by_country
                                ,by = 'country'
                                )


# INSPECT
df.map_public_debt %>% glimpse()


#============================
# PLOT
# - this is just a basic plot
#============================
df.map_public_debt %>% 
  ggplot(aes(x = long, y = lat, group = group)) +
    geom_polygon(aes(fill = debt_as_pct_of_gdp))


#=============
# CREATE THEME
#=============
theme.map &lt;- theme(
  text = element_text(family = 'Helvetica Neue', color = '#444444')
  ,panel.background = element_rect(fill = '#CCCCCC')
  ,plot.background = element_rect(fill = '#CCCCCC')
  ,legend.background = element_rect(fill = '#CCCCCC')
  ,panel.grid = element_blank()
  ,plot.title = element_text(size = 18, face = 'bold')
  ,plot.subtitle = element_text(size = 12)
  ,legend.key = element_blank()
  ,axis.text = element_blank()
  ,axis.ticks = element_blank()
  ,axis.title = element_blank()
)


#========================
# CREATE WORLD PLOT / MAP
#========================
plot.debt_to_gdp_map &lt;- df.map_public_debt %>% 
  ggplot(aes(x = long, y = lat, group = group)) +
  geom_polygon(aes(fill = debt_as_pct_of_gdp)) +
  theme.map +
  labs(title = str_c('Countries in the developed world are'
                     ,'\ncarrying high levels of debt compared to GDP'
                     )
       ,fill = str_c('Net public debt','\nas a % of GDP')
       ) +
  scale_fill_gradientn(colors = c('#009933', '#ffff00', 'orange', '#e60000')
                       ,values = scales::rescale(c(30, 50, 70, 100, 200))
                       )

</pre>
<p>Here, we’ll actually plot this two different times. </p>
<p>First, we’ll plot the entire map of the world.</p>
<pre class="wp-code-highlight">
#------
# WORLD
#------
plot.debt_to_gdp_map
</pre>
<p><a rel="nofollow" href="http://www.sharpsightlabs.com/join-newsletter-get-crash-course/" target="_blank"><br>
<img sizes="(max-width: 1832px) 100vw, 1832px" src="https://i2.wp.com/www.sharpsightlabs.com/wp-content/uploads/2018/03/world_debt_map.png?w=450" alt="" class="wp-image-3412" data-recalc-dims="1"><br>
</a></p>
<p>Next, we’ll sub-set this down and look only at a specific region: Europe.</p>
<p>To do this, we can use <code>coord_cartesian()</code> to specify a specific range for lat/long. This essentially “zooms in” on a specific part of the map.</p>
<pre class="wp-code-highlight">
#-------
# EUROPE
#-------
plot.debt_to_gdp_map + 
  coord_cartesian(xlim = c(-15, 50), ylim = c(30, 75)) +
  labs(title = &quot;European countries have high levels of public debt&quot;
       ,subtitle = str_c('In particular, countries in southern Europe - including Portugal, Italy,'
                         ,'\nGreece, and Spain - have high levels of public debt.'
                         )
       )
  
</pre>
<p><a rel="nofollow" href="http://www.sharpsightlabs.com/join-newsletter-get-crash-course/" target="_blank"><br>
<img sizes="(max-width: 1358px) 100vw, 1358px" src="https://i2.wp.com/www.sharpsightlabs.com/wp-content/uploads/2018/03/euro_debt_map.png?w=450" alt="" class="wp-image-3411" data-recalc-dims="1"><br>
</a></p>
<h1>Discover how to master data science</h1>
<p>Mastering data science takes practice and hard work. </p>
<p>Don’t try to figure it out alone. <a rel="nofollow" href="http://www.sharpsightlabs.com/join-newsletter-get-crash-course/" target="_blank">Sign up now</a>, and discover how to master data science. </p>
<p>In our tutorials, we will help you learn and master the tools you need to be a top-performing data scientist.</p>
<p>Moreover, if you sign up now, you’ll get access to our <strong>free</strong> Data Science Crash Course.</p>
<p>In the Data Science Crash Course, you’ll learn:</p>
<ul>
<li>a step-by-step data science learning plan </li>
<li>the 1 programming language you <i>need to</i> learn </li>
<li>3 essential data visualizations</li>
<li>how to do data manipulation in R</li>
<li>how to get started with machine learning</li>
<li>the difference between machine learning and statistics</li>
</ul>
<p><a rel="nofollow" href="http://www.sharpsightlabs.com/join-newsletter-get-crash-course/" target="_blank">
<p><strong>SIGN UP NOW</strong></p>
<p></p></a>
<p>The post <a rel="nofollow" href="http://www.sharpsightlabs.com/blog/map-public-debt-ggplot2/" target="_blank">How to map public debt data with ggplot2</a> appeared first on <a rel="nofollow" href="http://www.sharpsightlabs.com/" target="_blank">SHARP SIGHT</a>.</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="http://www.sharpsightlabs.com/blog/map-public-debt-ggplot2/"> r-bloggers | SHARP SIGHT</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/MM0Imu2yx5A" height="1"></a></div>