Session 7

Data and Interactive Maps

US Census

World Population

Shale Gaz Extraction in the U.S.: Perspectives from Geo-Located Twitter Conversations

UK’s 2015 Election Results

Flexdashboards

New Zealand’s Dashboards

Objectives

At the end of this session, you should be able to:

  1. retrieve map data
  2. produce static maps
  3. create interactive maps
  4. create flexdashboards

Plan

Plan

  • 7.1 Maps
  • 7.2 Map data
  • 7.3 Leaflet
  • 7.4 Create Flexdashboards
  • 7.5 Mission Impossible : Bar chart and Map

TL;DR

Maps

library(ggplot2)

library(rnaturalearth)
library(sf)
world <- ne_countries(scale = "medium", returnclass = "sf")
# Geom_sf 
ggplot(data = world) + 
  geom_sf(color = "black", fill = "lightgreen")
# Coord_sf
ggplot(data = world) +
    geom_sf() +
    coord_sf(crs = "+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs")
ggplot(data = world) +
    geom_sf() +
    coord_sf(xlim = c(-102.15, -74.12), ylim = c(7.65, 33.97))

world2 <- map_data('world')
# Geom_map
ggplot() + 
  geom_map(data=world2, map=world2, aes(x=long, y=lat, group=group, map_id=region)) + 
  coord_fixed(1.9, xlim = c(-100,175), ylim = c(-50,50))

usa <- map_data("usa")
state <- map_data("state")
cities <- read_tsv('https://assets.datacamp.com/production/course_862/datasets/US_Cities.txt')
library(dplyr)
pop <- aggregate(Pop_est ~ State, data = cities, sum)
names(pop)[names(pop) == "State"] <- "region"
pop$region <- tolower(pop$region)
statePop <- left_join(state, pop, by="region")
# Geom_polygon
ggplot(usa, aes(x = long, y = lat)) +
  geom_polygon() 
ggplot(state, aes(x = long, y = lat, fill = region, group=group)) +
  geom_polygon(col = "white") +
  theme(legend.position = "none")
ggplot(statePop, aes(x = long, y = lat, fill = Pop_est, group = group)) +
  geom_polygon(col = "white")
# Coord_map
ggplot(state, aes(x = long, y = lat, group=group)) +
  geom_polygon() +
  coord_map("gilbert") 
# Geom_points
ggplot(data = usa, aes(x = long, y = lat, group = group)) +
  geom_polygon() +
  geom_point(data = cities, aes(group = State, size = Pop_est), col = "red", shape = 19, alpha = 0.6) +
  coord_map()

Map data

library(ggplot2)
# World
world <- map_data("world")
ggplot(data = world, aes(x = long, y = lat, group = group)) + 
  geom_polygon(fill = "white", color = "black") +
  theme_void()

# Continents
# Europe
world <- map_data("world")
europe <- subset(world, region %in% c("Albania", "Andorra", "Armenia", "Austria", "Azerbaijan",
                                      "Belarus", "Belgium", "Bosnia and Herzegovina", "Bulgaria",
                                      "Croatia", "Cyprus", "Czechia","Denmark","Estonia","Finland", 
                                      "France","Georgia", "Germany", "Greece","Hungary","Iceland", 
                                      "Ireland", "Italy","Kazakhstan", "Kosovo", "Latvia","Liechtenstein", 
                                      "Lithuania", "Luxembourg","Malta","Moldova","Monaco","Montenegro",
                                      "Macedonia", "Netherlands","Norway","Poland","Portugal","Romania",
                                      "Russia","San Marino","Serbia","Slovakia","Slovenia","Spain",
                                      "Sweden","Switzerland","Turkey","Ukraine","UK","Vatican"))
ggplot(data = europe, aes(x = long, y = lat, group = group)) + 
  geom_polygon(fill = "white", color = "black") +
  theme_void() +
  coord_fixed(ratio=1.6, xlim = c(-50, 80))
# Americas
world <- map_data("world")
americas <- subset(world, region %in% c("USA","Brazil","Mexico", "Colombia", "Argentina", "Canada",
                                      "Peru","Venezuela","Chile","Guatemala","Ecuador", "Bolivia", "Cuba",
                                      "Honduras", "Paraguay", "Nicaragua","El Salvador", "Costa Rica", 
                                      "Panama", "Uruguay",  "Jamaica",  "Trinidad and Tobago", "Guyana", 
                                      "Suriname", "Belize", "Barbados", "Saint Lucia", "Grenada", 
                                      "Saint Vincent and the Grenadines", "Antigua and Barbuda", 
                                      "Saint Kitts and Nevis"))
ggplot(data = americas, aes(x = long, y = lat, group = group)) + 
  geom_polygon(fill = "white", color = "black") +
  coord_fixed(ratio=1.1, xlim = c(-180, -35))  + 
  theme_void() 
# Oceania
world <- map_data("world")
oceania <- subset(world, region %in% c("Australia", "Fiji", "Kiribati", "Marshall Islands", "Micronesia", 
                                      "Nauru", "New Zealand", "Palau"," Papua New Guinea", "Samoa", 
                                      "Solomon Islands", "Tonga", "Tuvalu", "Vanuatu"))
ggplot(data = oceania, aes(x = long, y = lat, group = group)) + 
  geom_polygon(fill = "white", color = "black") +
  coord_fixed(xlim = c(110,180)) +
  theme_void()
# Asia 
world <- map_data("world")
asia <- subset(world, region %in% c("Afghanistan", "Armenia", "Azerbaijan", "Bahrain", "Bangladesh", "Bhutan", 
                                    "Brunei", "Cambodia", "China", "Cyprus", "Georgia", "India", "Indonesia", 
                                    "Iran", "Iraq", "Israel", "Japan", "Jordan", "Kazakhstan", "Kuwait", 
                                    "Kyrgyzstan", "Laos", "Lebanon", "Malaysia", "Maldives", "Mongolia", 
                                    "Myanmar", "Nepal", "North Korea", "Oman", "Pakistan", "Palestine", 
                                    "Philippines", "Qatar", "Russia", "Saudi Arabia", "Singapore", 
                                    "South Korea", "Sri Lanka", "Syria", "Taiwan", "Tajikistan", "Thailand", 
                                    "Timor-Leste", "Turkey", "Turkmenistan", "United Arab Emirates", 
                                    "Uzbekistan", "Vietnam", "Yemen"))
ggplot(data = asia, aes(x = long, y = lat, group = group)) + 
  geom_polygon(fill = "white", color = "black") +
  coord_fixed(1.2) +
  theme_void()
# Africa
world <- map_data("world")
africa <- subset(world, region %in% c("Algeria","Angola","Benin","Botswana","Burkina Faso","Burundi",
                                      "Cabo Verde","Cameroon","Central African Republic","Chad","Comoros",
                                      "Democratic Republic of the Congo","Republic of Congo","Ivory Coast",
                                      "Djibouti","Egypt","Equatorial Guinea","Eritrea","Swaziland","Ethiopia",
                                      "Gabon","Gambia","Ghana","Guinea","Guinea-Bissau","Kenya","Lesotho",
                                      "Liberia","Libya","Madagascar","Malawi","Mali","Mauritania","Mauritius",
                                      "Morocco", "Mozambique","Namibia","Niger","Nigeria","Rwanda",
                                      "Sao Tome and Principe", "Senegal","Seychelles","Sierra Leone","Somalia",
                                      "South Africa","South Sudan", "Sudan","Tanzania","Togo","Tunisia",
                                      "Uganda", "Zambia","Zimbabwe"))
ggplot(data = africa, aes(x = long, y = lat, group = group)) + 
  geom_polygon(fill = "white", color = "black") +
  coord_fixed() + 
  theme_void() 

# Countries
nigeria <- subset(world, region %in% c("Nigeria"))
ggplot(data = africa, aes(x = long, y = lat, group = group)) + 
  geom_polygon(data = africa, fill = "white", color = "black") +
  geom_polygon(data = nigeria, fill = "gray", color = "black") +
  coord_fixed() + 
  theme_void() 
# Nigeria
nigeria <- map_data("world", region = "Nigeria")
ggplot(data = nigeria, aes(x = long, y = lat, group = group)) + 
  geom_polygon(fill = "white", color = "black") +
  coord_fixed() + 
  theme_void() 
# Canada
canada <- map_data("world", region = "Canada")
ggplot(data=canada, aes(x = long, y = lat, group = group)) +
  geom_polygon(fill = "white", color="black")+
  coord_fixed(1.8) + 
  theme_void()
# China
china <- map_data("world", region = "China")
ggplot(china, aes(x = long, y = lat, group = group)) +
  geom_polygon(fill = "white", color="black")+
  coord_fixed(1.3) + 
  theme_void() 
# USA
usa <- map_data("world", region = "USA")
ggplot(data=usa, aes(x = long, y = lat, group = group)) +
  geom_polygon(fill = "white", color = "black")+
  coord_fixed(1.8, xlim = c(-180,0)) + 
  theme_void()
(mainland <- ggplot(data=usa, aes(x = long, y = lat, group = group)) +
              geom_polygon(fill = "white", color = "black")+
              coord_fixed(1.5, xlim = c(-125,-68), ylim = c(50,22)) + 
              theme_void())
(alaska <- ggplot(data = usa, aes(x = long, y = lat, group = group)) +
              geom_polygon(fill = "white", color = "black") +
              coord_fixed(1.6, xlim = c(-178,-132), ylim = c(52,71)) + 
              theme_void())
(hawaii <- ggplot(data=usa, aes(x = long, y = lat, group = group)) +
            geom_polygon(fill = "white", color = "black") +
            coord_fixed(1.5, xlim = c(-162,-153), ylim = c(23,18)) + 
            theme_void())
ratioAlaska <- (25 - 2) / (16 - (-24))
ratioHawaii  <- (23 - 18) / (-154 - (-161))
library(cowplot)
ggdraw(mainland) +
  draw_plot(alaska, width = 0.26, height = 0.26 * 10/6 * ratioAlaska, x = 0.1, y = 0.01) +
  draw_plot(hawaii, width = 0.15, height = 0.15 * 10/6 * ratioHawaii, x = 0.3, y = 0.01)

# States
usa <- map_data("world", region = "USA")
usa_mainland <- subset(usa, subregion != "Alaska")
usa_mainland <- subset(usa_mainland, subregion != "Hawaii")
usa_states <- map_data("state")
ggplot(data = usa_mainland, aes(x = long, y = lat, group = group)) + 
  geom_polygon(data = usa_states, fill = "white", color = "black") +
  coord_fixed(1.4) + 
  theme_void() 
# Nevada
nevada <- subset(usa_states, region == "nevada")
ggplot(data = usa_states, aes(x = long, y = lat, group = group)) + 
  geom_polygon(data = usa_states, fill = "white", color = "black") +
  geom_polygon(data = nevada, fill = "gray", color = "black") +
  coord_fixed(1.4) + 
  theme_void() 
ggplot(data = nevada, aes(x = long, y = lat, group = group)) + 
  geom_polygon(fill = "white", color = "black") +
  coord_fixed(1.4) + 
  theme_void() 
# Texas 
texas <- subset(usa_states, region == "texas")
ggplot(data = texas, aes(x = long, y = lat, group = group)) + 
  geom_polygon(fill = "white", color = "black") +
  coord_fixed(1.4) + 
  theme_void() 
# California
california <- subset(usa_states, region == "california")
ggplot(data = california, aes(x = long, y = lat, group = group)) + 
  geom_polygon(fill = "white", color = "black") +
  coord_fixed(1.4) + 
  theme_void() 

# Counties
usa_counties <- map_data("county")
california_counties <- subset(usa_counties, region == "california")
losAngeles <- subset(california_counties, subregion == "los angeles")
ggplot(data = california, aes(x = long, y = lat, group = group)) + 
  geom_polygon(data = california_counties, fill = "white", color = "black") +
  geom_polygon(data = losAngeles, fill = "gray", color = "black") +
  coord_fixed(1.4) + 
  theme_void() 

# Cities
# Los angeles
ggplot(data = losAngeles, aes(x = long, y = lat, group = group)) + 
  geom_polygon(fill = "white", color = "black") +
  coord_fixed(1.4) + 
  theme_void() 
# San Francisco
sanFrancisco <- subset(california_counties, subregion == "san francisco")
ggplot(data = sanFrancisco, aes(x = long, y = lat, group = group)) + 
  geom_polygon(fill = "white", color = "black") +
  coord_fixed(1.4) + 
  theme_void() 

# Associations and Agreements
# European Union
world <- map_data("world")
european.union.countries <- c("Bulgaria","Cyprus","Estonia","Finland","Greece","Ireland","Latvia",
                              "Lithuania","Luxembourg","Malta","Romania" ,"Sweden","Portugal", 
                              "Spain", "France", "Switzerland", "Germany","Austria", "Belgium", 
                              "UK", "Netherlands", "Denmark", "Poland", "Italy", "Croatia", 
                              "Slovenia", "Hungary", "Slovakia", "Czech republic")
european.union <- map_data("world", region = european.union.countries)
ggplot(european.union, aes(x = long, y = lat)) +
  geom_polygon(aes(group = group), fill = "white", color="black") +
  coord_fixed(1.2) + 
  theme_void() 
# NAFTA
NAFTA.countries <- c("USA","Canada", "Mexico")
NAFTA <- map_data("world", region = NAFTA.countries)
ggplot(NAFTA, aes(x = long, y = lat, group = group)) +
  geom_polygon(fill = "white", color="black") +
  coord_fixed(1.2, xlim = c(-175,-55)) +
  theme_void()

# Campuses
# SKEMA 
world <- subset(world, region != "Antarctica")
world <- subset(world, region != "French Southern and Antarctic Lands")
skema.campuses <- subset(world, region %in% c("France", "USA", "China", "South Africa", "Brazil"))
skema.campuses$code <- 1
skema.campuses.alaska <- subset(skema.campuses, subregion %in% c("Alaska"))
skema.campuses.alaska$code <- 2
ggplot(data = world, aes(x = long, y = lat, group = group)) + 
  geom_polygon(fill = "white", color = "black", size = 0.3) +
  geom_polygon(data = skema.campuses, aes(fill = code), color = "black", size = 0.3) +
  geom_polygon(data = skema.campuses.alaska, aes(fill = code), color = "black", size = 0.3) +
  scale_fill_gradient(low = "gray", high = "white") +
  coord_fixed(1.5) +
  theme_void() + 
  theme(legend.position = "none")

Leaflet

library(leaflet)
# Without Marker 
leaflet() %>% 
  setView(lng = -73.582189, lat = 45.517958, zoom = 13) %>% 
  addTiles()

# With Marker
leaflet() %>% 
  addTiles() %>%
  addMarkers(lng=-73.582189, lat=45.517958, popup="The birthplace of SKEMA Quantum Studio")

# Marker & Zoom
leaflet(options = leafletOptions(minZoom = 0, maxZoom = 18)) %>% 
  addTiles() %>%
  addMarkers(lng=-73.582189, lat=45.517958, popup="The birthplace of SKEMA Quantum Studio")

# Data Object
library(maps)
usa_states = map("state", fill = TRUE, plot = FALSE)
leaflet(data = usa_states) %>% 
  addTiles() %>%
  addPolygons(fillColor = topo.colors(10, alpha = NULL), stroke = FALSE)
skema.campuses <- data.frame(country=c("United States", "Brazil", "South Africa", "China", 
                                       "France", "France", "France"), 
                             city=c("Raleigh", "Belo Horizonte", "Cap Town", "Suzhou", 
                                    "Paris", "Lille", "Sophia Antipolis"),
                             lng=c(-80.793457, -43.940933, 18.423300, 120.599998, 
                                   2.349014, 3.05858, 7.25),
                             lat=c(35.782169, -19.912998, -33.918861, 31.299999, 
                                   48.864716, 50.63297, 43.7))
leaflet(data = skema.campuses) %>%
  addTiles() %>%
  addMarkers(lng=~lng, lat=~lat, popup=~country)

# Customizing Marker Icons
greenLeafIcon <- makeIcon(
  iconUrl = "http://leafletjs.com/examples/custom-icons/leaf-green.png",
  iconWidth = 38, iconHeight = 95,
  iconAnchorX = 22, iconAnchorY = 94,
  shadowUrl = "http://leafletjs.com/examples/custom-icons/leaf-shadow.png",
  shadowWidth = 50, shadowHeight = 64,
  shadowAnchorX = 4, shadowAnchorY = 62)
leaflet(data = skema.campuses) %>%
  addTiles() %>%
  addMarkers(lng=~lng, lat=~lat, popup=~country, icon = greenLeafIcon)

skema.campuses$language <- ifelse(skema.campuses$country == "France", "French", "English") 
leafIcons <- icons(
  iconUrl = ifelse(skema.campuses$language == "French",
    "http://leafletjs.com/examples/custom-icons/leaf-red.png",
    "http://leafletjs.com/examples/custom-icons/leaf-green.png"),
  iconWidth = 38, iconHeight = 95,
  iconAnchorX = 22, iconAnchorY = 94,
  shadowUrl = "http://leafletjs.com/examples/custom-icons/leaf-shadow.png",
  shadowWidth = 50, shadowHeight = 64,
  shadowAnchorX = 4, shadowAnchorY = 62)
leaflet(data = skema.campuses) %>% addTiles() %>%
  addMarkers(~lng, ~lat, icon = leafIcons)

skema.campuses$continent <- ifelse(skema.campuses$country == c("United States", "Brazil"), "Americas", 
                                   ifelse(skema.campuses$country == "France", "Europe", "RoW"))
skema.campuses$code <- ifelse(skema.campuses$country == c("United States", "Brazil"), 1, 
                              ifelse(skema.campuses$country == "France", 2, 3))

getColor <- function(campuses){
  sapply(skema.campuses$code, function(code){
  if(code == 1){
    "green"
  } else if(code == 2){
    "red"
  } else {
    "orange"
  }})
  }
icons <- awesomeIcons(
  icon = 'ios-close',
  iconColor = 'black',
  library = 'ion',
  markerColor = getColor(skema.campuses))

leaflet(skema.campuses) %>% addTiles() %>%
  addAwesomeMarkers(~lng, ~lat, icon=icons, label=~as.character(continent))

leaflet(skema.campuses) %>% 
  addTiles() %>% 
  addMarkers(clusterOptions = markerClusterOptions())

leaflet(skema.campuses) %>% 
  addTiles() %>% 
  addCircleMarkers()

pal <- colorFactor(c("navy", "red"), domain = c("English", "French"))

leaflet(skema.campuses) %>% 
  addTiles() %>%
  addCircleMarkers(
    radius = ~ifelse(language == "French", 6, 10),
    color = ~pal(language),
    stroke = FALSE, 
    fillOpacity = 0.5
  )

leaflet(data = skema.campuses) %>%
  addTiles() %>%
  addMarkers(lng=~lng, lat=~lat, popup=~city)

content <- paste(sep = "<br/>",
  "<b><a href='https://quantumstudio.skemagloballab.io/'>SKEMA Quantum Studio</a></b>",
  "4200 Saint Laurent Blvd",
  "Montréal, QC H2W2R2"
)

leaflet() %>% addTiles() %>%
  addPopups(lng = -73.582189, lat = 45.517958, content,
    options = popupOptions(closeButton = FALSE)
  )

library(htmltools)

leaflet(skema.campuses) %>% 
  addTiles() %>%
  addMarkers(~lng, ~lat, label = ~htmlEscape(country))

leaflet() %>% 
  addTiles() %>% 
  setView(-2.349014, 48.864716, 2) %>%
  addMarkers(
    lng = -80.793457, lat = 35.782169,
    label = "Default Label",
    labelOptions = labelOptions(noHide = T)) %>%
  addMarkers(
    lng = -43.940933, lat = -19.912998,
    label = "Label without surrounding box",
    labelOptions = labelOptions(noHide = T, textOnly = TRUE)) %>%
  addMarkers(
    lng = 18.423300, lat = -33.918861,
    label = "label with textsize 15px",
    labelOptions = labelOptions(noHide = T, textsize = "15px")) %>%
  addMarkers(
    lng = 120.599998, lat = 31.299999,
    label = "hidden label with textsize 12px",
    labelOptions = labelOptions(noHide = F, textsize = "10px")) %>%
  addMarkers(
    lng = 2.349014, lat = 48.864716,
    label = "Label w/ custom CSS style",
    labelOptions = labelOptions(noHide = T, direction = "bottom",
      style = list(
        "color" = "red",
        "font-family" = "serif",
        "font-style" = "italic",
        "box-shadow" = "3px 3px rgba(0,0,0,0.25)",
        "font-size" = "12px",
        "border-color" = "rgba(0,0,0,0.5)"
      )))

leaflet() %>% 
  addTiles() %>%
  addLabelOnlyMarkers(data = skema.campuses, lng = ~lng, lat = ~lat, label = ~as.character(city), 
                      labelOptions = labelOptions(noHide = T, direction = 'top', textOnly = T))

skema.students <- data.frame(city=c("Raleigh", "Belo Horizonte", "Cap Town", "Suzhou", "Paris", "Lille", "Sophia Antipolis"),
                             students=c(800, 1500, 500, 2500, 1500, 1200, 1000))
library(dplyr)
skema.campuses <- left_join(skema.campuses, skema.students, by="city")

leaflet(skema.campuses) %>% 
  addTiles() %>%
  addCircles(lng = ~lng, lat = ~lat, weight = 10, radius = ~students * 200, popup = ~city)

leaflet() %>% 
  addTiles() %>%
  addRectangles(
    lng1=-73.582189, lat1=45.517958,
    lng2=-73.582700, lat2=45.517500,
    fillColor = "transparent"
  )

leaflet() %>% setView(lng = -73.656830 , lat = 45.516136, zoom = 12) %>% 
  addTiles()

leaflet() %>% setView(lng = -73.656830 , lat = 45.516136, zoom = 12) %>% 
  addProviderTiles(providers$Stamen.Toner)

leaflet() %>% setView(lng = -73.656830 , lat = 45.516136, zoom = 12) %>% 
  addProviderTiles(providers$MtbMap) %>%
  addProviderTiles(providers$Stamen.TonerLines, options = providerTileOptions(opacity = 0.35)) %>%
  addProviderTiles(providers$Stamen.TonerLabels)

leaflet() %>% addTiles() %>% setView(-93.65, 42.0285, zoom = 4) %>%
  addWMSTiles(
    "http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi",
    layers = "nexrad-n0r-900913",
    options = WMSTileOptions(format = "image/png", transparent = TRUE),
    attribution = "Weather data © 2012 IEM Nexrad"
  )

Mission Impossible

Your mission, should you choose to accept it…

… is to create a bar chart and a map on SKEMA Quantum Studio!

You must use the previous data and calculate the mean gdp per country. With the results, you will create a bar chart identical to the one in the exercise.

Next, you have to produce a map from the capitals, the longitudes and the latitudes present in the data. Once again, your map must be identical to ours.

Pay attention, every little detail is important!

We recommend you to review your courses on the Virtual Campus.