This text is dedicated to map making with R. More information can be found in the book Geocomputation with R

Loading required packages

library(sf)
## Warning: package 'sf' was built under R version 3.6.3
## Linking to GEOS 3.6.1, GDAL 2.2.3, PROJ 4.9.3
library(raster)
## Warning: package 'raster' was built under R version 3.6.3
## Loading required package: sp
## Warning: package 'sp' was built under R version 3.6.3
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:raster':
## 
##     intersect, select, union
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(spData)
## Warning: package 'spData' was built under R version 3.6.3
## To access larger datasets in this package, install the spDataLarge
## package with: `install.packages('spDataLarge',
## repos='https://nowosad.github.io/drat/', type='source')`
# visualization map packages
library(tmap)    # for static and interactive maps
## Warning: package 'tmap' was built under R version 3.6.3
library(leaflet) # for interactive maps
## Warning: package 'leaflet' was built under R version 3.6.3
library(mapview) # for interactive maps
## Warning: package 'mapview' was built under R version 3.6.3
library(ggplot2) # tidyverse data visualization package
## Warning: package 'ggplot2' was built under R version 3.6.3
library(shiny)   # for web applications
## Warning: package 'shiny' was built under R version 3.6.3

Static Map

# Add fill layer to nz shape
tm_shape(nz) + tm_fill() 

# Add border layer to nz shape
tm_shape(nz) + tm_borders() 

# Add fill and border layers to nz shape
tm_shape(nz) +  tm_fill(col="green") + tm_borders(col="red") 

Full list of tm_ functions help("tmap-element")

ma1 = tm_shape(nz) + tm_fill(col = "red")
ma2 = tm_shape(nz) + tm_fill(col = "red", alpha = 0.3)
ma3 = tm_shape(nz) + tm_borders(col = "blue")
ma4 = tm_shape(nz) + tm_borders(lwd = 3)
ma5 = tm_shape(nz) + tm_borders(lty = 2)
ma6 = tm_shape(nz) + tm_fill(col = "red", alpha = 0.3) +
  tm_borders(col = "blue", lwd = 3, lty = 2)
tmap_arrange(ma1, ma2, ma3, ma4, ma5, ma6)

legend_title = expression("Area (km"^2*")")
tm_shape(nz) +tm_fill(col = "Land_area", title = legend_title) + tm_borders()

Color Setting

m1<-tm_shape(nz) + tm_polygons(col = "Median_income")
breaks = c(0, 3, 4, 5) * 10000
m2<-tm_shape(nz) + tm_polygons(col = "Median_income", breaks = breaks)
m3<-tm_shape(nz) + tm_polygons(col = "Median_income", n = 10)
m4<-tm_shape(nz) + tm_polygons(col = "Median_income", palette = "BuGn") + tm_compass(type = "4star", position = c("right", "top")) +  tm_scale_bar(breaks = c(0, 50, 100,150,200), text.size = 1)

tmap_arrange(m1,m2,m3,m4)

Interactive Map

tmap_mode("view")
## tmap mode set to interactive viewing
m4
## Compass not supported in view mode.
library(mapdeck)
## Warning: package 'mapdeck' was built under R version 3.6.3
set_token(Sys.getenv("MAPBOX"))
crash_data = read.csv("https://git.io/geocompr-mapdeck")
crash_data = na.omit(crash_data)
ms = mapdeck_style("dark")
mapdeck(style = ms, pitch = 45, location = c(0, 52), zoom = 4) %>%
add_grid(data = crash_data, lat = "lat", lon = "lng", cell_size = 1000,
         elevation_scale = 50, layer_id = "grid_layer",
         colour_range = viridisLite::plasma(6))
## Registered S3 method overwritten by 'jsonify':
##   method     from    
##   print.json jsonlite
pal = colorNumeric("RdYlBu", domain = cycle_hire$nbikes)
leaflet(data = cycle_hire) %>% 
  addProviderTiles(providers$Stamen) %>%
  addCircles(col = ~pal(nbikes), opacity = 0.9) %>% 
  addPolygons(data = lnd, fill = FALSE) %>% 
  addLegend(pal = pal, values = ~nbikes) %>% 
  setView(lng = -0.1, 51.5, zoom = 12) %>% 
  addMiniMap()
library(shiny)    # for shiny apps
library(leaflet)  # renderLeaflet function
library(spData)   # loads the world dataset 
ui = fluidPage(sliderInput(inputId = "life", "Life expectancy", 49, 84, value = 80),leafletOutput(outputId = "map"))
server = function(input, output) {
  output$map = renderLeaflet({
    leaflet() %>% 
      # addProviderTiles("OpenStreetMap.BlackAndWhite") %>%
      addPolygons(data = world[world$lifeExp < input$life, ])})
}
shinyApp(ui, server)
## PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.

Shiny applications not supported in static R Markdown documents
# Map with ggplot2

library(ggplot2)
g1 = ggplot() + geom_sf(data = nz, aes(fill = Median_income)) +
  geom_sf(data = nz_height) +
  scale_x_continuous(breaks = c(170, 175))
g1

Applications in Ecology

library(sf)
library(dplyr)
library(tmap)         # visualization package (see Chapter 8)
library(osrm)         # routing package
## Warning: package 'osrm' was built under R version 3.6.3
## Data: (c) OpenStreetMap contributors, ODbL 1.0 - http://www.openstreetmap.org/copyright
## Routing: OSRM - http://project-osrm.org/
library(vegan)
## Warning: package 'vegan' was built under R version 3.6.3
## Loading required package: permute
## Warning: package 'permute' was built under R version 3.6.3
## Loading required package: lattice
## This is vegan 2.5-6
library(reticulate)
## Warning: package 'reticulate' was built under R version 3.6.3

Trying some Python codes in R

To work with Python in R, we need to import reticulate package

def myfunction(x,y):
  z=x+y*12
  return z
myfunction(3,4)
# For loop 
## 51
for i in range(1,10):
  print("This is number:", i)
  
## This is number: 1
## This is number: 2
## This is number: 3
## This is number: 4
## This is number: 5
## This is number: 6
## This is number: 7
## This is number: 8
## This is number: 9
import numpy as np