<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/mapping-oil-production-by-country-in-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://sharpsightlabs.com/blog/map-oil-production-country-r/"> r-bloggers – SHARP SIGHT LABS</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><a href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/"><br>
<img sizes="(max-width: 1554px) 100vw, 1554px" src="https://i0.wp.com/sharpsightlabs.com/wp-content/uploads/2017/12/oil_production_bbl-per-day_2016_v2.png?w=450" alt="" class="wp-image-3194" data-recalc-dims="1"><br>
</a></p>
<p>This week, here’s another map. </p>
<p>As I’ve mentioned, projects like this – a few hundred lines of code, with a variety of functions from the tidyverse – are excellent practice for intermediate data scientists.</p>
<p>But if you’re a beginner, don’t be intimidated. You can actually learn these tools <a href="http://sharpsightlabs.com/blog/rapidly-master-data-science/">much faster than you think</a>.</p>
<p>To get to a point where you really know how this works, you’ll need a few things. You will need to know a <a href="http://sharpsightlabs.com/blog/start-with-data-visualization-manipulation/">few things about ggplot2</a>, <a href="http://sharpsightlabs.com/blog/dplyr-intro-data-manipulation-with-r/">dplyr</a> and the tidyverse. I recommend that you break this down, line by line. Do you know all of the functions? Do you know how it all works? If you don’t, you might have some more practice to do. </p>
<p>Ultimately, to be <a href="http://sharpsightlabs.com/blog/are-you-fluent-r/">“fluent” in data science</a> in R, you should be able to write this code (or something like it) from scratch, more or less from memory.</p>
<p>In any case, there’s a lot going on in this code.</p>
<p>In a separate post, I will explain a few details about how this works, and expand on it somewhat.</p>
<p>In the meantime, if you want to learn to do projects like this, go through the code below. <a href="http://sharpsightlabs.com/blog/simple-practice-data-wrangling-iris-dataset/">Break it down into small pieces</a> that you can study and practice. </p>
<p>And if you want to know more about data visualization and data science in R, <a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank">sign up for our email list.</a></p>
<h1>Sign up now, and discover how to rapidly master data science</h1>
<p>To master data visualization and data science, you need to master the essential tools.</p>
<p>Moreover, to make rapid progress, you need to know what to learn, what <em>not</em> to learn, and you need to know <em>how to practice</em> what you learn.</p>
<p>Sharp Sight is dedicated to teaching you how to master the tools of data science as quickly as possible.</p>
<p><a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank">Sign up now for our email list</a>, and you’ll receive regular tutorials and lessons. </p>
<p>You’ll learn:</p>
<ul>
<li>How to do data visualization in R</li>
<li>How to practice data science</li>
<li>How to apply data visualization to more advanced topics (like machine learning)</li>
<li>… and more </li>
</ul>
<p>If you <a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank">sign up for our email list <em>right now</em></a>, you’ll also get access to our “Data Science Crash Course” <u>for free</u>.</p>
<p><a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank">
<p><strong>SIGN UP NOW</strong></p>
<p></p></a>
<p> </p>
<h1>Code: mapping oil production by country</h1>
<pre class="wp-code-highlight">

#==============
# LOAD PACKAGES
#==============

library(tidyverse)
library(sf)
library(rvest)
library(stringr)
library(scales)
#library(viridis)



#============
# SCRAPE DATA
#============

df.oil &lt;- read_html(&quot;https://en.wikipedia.org/wiki/List_of_countries_by_oil_production&quot;) %>%
  html_nodes(&quot;table&quot;) %>%
  .[[1]] %>%
  html_table()



#====================
# CHANGE COLUMN NAMES 
#====================

colnames(df.oil) &lt;- c('rank', 'country', 'oil_bbl_per_day')



#=============================
# WRANGLE VARIABLES INTO SHAPE
#=============================


#----------------------------------
# COERCE 'rank' VARIABLE TO INTEGER
#----------------------------------

df.oil &lt;- df.oil %>% mutate(rank = as.integer(rank)) 

df.oil %>% glimpse()



#---------------------------------------------------
# WRANGLE FROM CHARACTER TO NUMERIC: oil_bbl_per_day
#---------------------------------------------------

df.oil &lt;- df.oil %>% mutate(oil_bbl_per_day = oil_bbl_per_day %>% str_replace_all(',','') %>% as.integer())


# inspect
df.oil %>% glimpse()


#===========================
#CREATE VARIABLE: 'opec_ind'
#===========================

df.oil &lt;- df.oil %>% mutate(opec_ind = if_else(str_detect(country, 'OPEC'), 1, 0))


#=========================================================
# CLEAN UP 'country'
# - some country names are tagged as being OPEC countries
#   and this information is in the country name
# - we will strip this information out
#=========================================================

df.oil &lt;- df.oil %>% mutate(country = country %>% str_replace(' \\(OPEC\\)', '') %>% str_replace('\\s{2,}',' '))


# inspect
df.oil %>% glimpse()


#------------------------------------------
# EXAMINE OPEC COUNTRIES
# - here, we'll just visually inspect
#   to make sure that the names are correct
#------------------------------------------

df.oil %>% 
  filter(opec_ind == 1) %>%
  select(country)



#==================
# REORDER VARIABLES
#==================

df.oil &lt;- df.oil %>% select(rank, country, opec_ind, oil_bbl_per_day)

df.oil %>% glimpse()



#========
# GET MAP
#========

map.world &lt;- map_data('world')

df.oil


#==========================
# CHECK FOR JOIN MISMATCHES
#==========================

anti_join(df.oil, map.world, by = c('country' = 'region'))


# rank                           country opec_ind oil_bbl_per_day
# 1   67 Congo, Democratic Republic of the        0          20,000
# 2   47               Trinidad and Tobago        0          60,090
# 3   34            Sudan and  South Sudan        0         255,000
# 4   30            Congo, Republic of the        0         308,363
# 5   20                    United Kingdom        0         939,760
# 6    3                     United States        0       8,875,817



#=====================
# RECODE COUNTRY NAMES
#=====================

map.world %>%
  group_by(region) %>%
  summarise() %>%
  print(n = Inf)


# UK
# USA
# Democratic Republic of the Congo
# Trinidad
# Sudan
# South Sudan


df.oil &lt;- df.oil %>%  mutate(country = recode(country, `United States` = 'USA'
                                 , `United Kingdom` = 'UK'
                                 , `Congo, Democratic Republic of the` = 'Democratic Republic of the Congo'
                                 , `Trinidad and Tobago` = 'Trinidad'
                                 , `Sudan and South Sudan` = 'Sudan'
                                 #, `Sudan and  South Sudan` = 'South Sudan'
                                 , `Congo, Republic of the` = 'Republic of Congo'
                                 )
                   )



#-----------------------
# JOIN DATASETS TOGETHER
#-----------------------

map.oil &lt;- left_join( map.world, df.oil, by = c('region' = 'country')) 



#=====
# PLOT
#=====

# BASIC (this is a first draft)

ggplot(map.oil, aes( x = long, y = lat, group = group )) +
  geom_polygon(aes(fill = oil_bbl_per_day))



#=======================
# FINAL, FORMATTED DRAFT
#=======================


df.oil %>% filter(oil_bbl_per_day > 822675) %>% summarise(mean(oil_bbl_per_day))
# 3190373

df.oil %>% filter(oil_bbl_per_day &lt; 822675) %>% summarise(mean(oil_bbl_per_day))
# 96581.08



ggplot(map.oil, aes( x = long, y = lat, group = group )) +
  geom_polygon(aes(fill = oil_bbl_per_day)) +
  scale_fill_gradientn(colours = c('#461863','#404E88','#2A8A8C','#7FD157','#F9E53F')
                       ,values = scales::rescale(c(100,96581,822675,3190373,10000000))
                       ,labels = comma
                       ,breaks = c(100,96581,822675,3190373,10000000)
                       ) +
  guides(fill = guide_legend(reverse = T)) +
  labs(fill = 'bbl/day'
       ,title = 'Oil Production by Country'
       ,subtitle = 'Barrels per day, 2016'
       ,x = NULL
       ,y = NULL) +
  theme(text = element_text(family = 'Gill Sans', color = '#EEEEEE')
        ,plot.title = element_text(size = 28)
        ,plot.subtitle = element_text(size = 14)
        ,axis.ticks = element_blank()
        ,axis.text = element_blank()
        ,panel.grid = element_blank()
        ,panel.background = element_rect(fill = '#333333')
        ,plot.background = element_rect(fill = '#333333')
        ,legend.position = c(.18,.36)
        ,legend.background = element_blank()
        ,legend.key = element_blank()
        ) +
  annotate(geom = 'text'
           ,label = 'Source: U.S. Energy Information Administration\nhttps://en.wikipedia.org/wiki/List_of_countries_by_oil_production'
           ,x = 18, y = -55
           ,size = 3
           ,family = 'Gill Sans'
           ,color = '#CCCCCC'
           ,hjust = 'left'
           )

</pre>
<p>And here’s the finalized map that the code produces:</p>
<p><a href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/"><br>
<img sizes="(max-width: 1554px) 100vw, 1554px" src="https://i0.wp.com/sharpsightlabs.com/wp-content/uploads/2017/12/oil_production_bbl-per-day_2016_v2.png?w=450" alt="" class="wp-image-3194" data-recalc-dims="1"><br>
</a></p>
<p>To get more tutorials that explain how this code works, sign up for our email list.</p>
<p><a rel="nofollow" href="http://sharpsightlabs.com/join-newsletter-rapid-mastery/" target="_blank">
<p><strong>SIGN UP NOW</strong></p>
<p></p></a>
<p>The post <a rel="nofollow" href="http://sharpsightlabs.com/blog/map-oil-production-country-r/" target="_blank">Mapping oil production by country in R</a> appeared first on <a rel="nofollow" href="http://sharpsightlabs.com/" target="_blank">SHARP SIGHT LABS</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://sharpsightlabs.com/blog/map-oil-production-country-r/"> r-bloggers – SHARP SIGHT LABS</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/TGwHuqlA-dA" height="1"></a></div>