class: center, middle, inverse, title-slide # Tutorial: Making maps with R ## 🗺
from base (rock) to shiny (clouds) ### Jannes Muenchow, Robin Lovelace ### eRum Budapest, 2018-05-14 --- layout: true background-image: url(img/r_geocomp_background.png) background-size: cover --- # A brief history of geographic vizualisation I - Neo Babylonian (626 BC - 539 BC) temple plan Source: (Talbert, 2014) <img src="img/neo-babylon-temple-map-circa-600-bc.png" width="50%" /> --- # A brief history of geographic vizualisation II - Neo Babylonian (626 BC - 539 BC) map of the world Source: (Talbert, 2014) <img src="img/babylon-map.png" width="50%" /> --- # A brief history of geographic vizualisation III - Humboldt's Naturgemälde (1807, *Geography of Plants*) ![](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7e/Zentralbibliothek_Z%C3%BCrich_-_Ideen_zu_einer_Geographie_der_Pflanzen_nebst_einem_Naturgem%C3%A4lde_der_Tropenl%C3%A4nder_-_000012142.jpg/2560px-Zentralbibliothek_Z%C3%BCrich_-_Ideen_zu_einer_Geographie_der_Pflanzen_nebst_einem_Naturgem%C3%A4lde_der_Tropenl%C3%A4nder_-_000012142.jpg)<!-- --> <!-- - The mappa mundi - largest Mediaval map surviving (~1300 **AD**) --> <!-- knitr::include_graphics("https://upload.wikimedia.org/wikipedia/commons/4/48/Hereford-Karte.jpg?download") --> --- # A brief history of geographic data viz in R "The core R engine was not designed specifically for the display and analysis of maps, and the limited interactive facilities it offers have drawbacks in this area" (Bivand, Pebesma, and Gómez-Rubio, 2013). -- Five years later... -- "An example showing R's flexibility and evolving geographic capabilities is **leaflet** (Cheng, Karambelkar, and Xie, 2018), a package for making interactive maps that has been extended by the R community, as we'll see in Chapter 9" (Lovelace, Nowosad, and Meunchow, 2018). --- # R's 'base' graphics: sp ![](04_viz_files/figure-html/unnamed-chunk-5-1.png)<!-- --> --- # Base R graphics: sp code Credit: [asdar-book.org/](http://asdar-book.org/), reproducible code accompanying the book Applied Spatial Data Analysis with R (Pebesma et al. 2013). ```r library(sp) library(spData) nz_sp = as(nz, "Spatial") plot(nz_height_sp, cex = 2) title("points") plot(nz_sp, col = "grey") plot(nz_height, add = TRUE, col = "red") ``` -- ## Observations - Passes arguments (e.g `cex` for symbol size) to `graphics::plot()` - New command for each additional 'layer' (e.g. `title()`, `plot(..., add = TRUE)`) - Black and white default output style - Fast --- # Base R graphics: sf ```r plot(nz) ``` ![](04_viz_files/figure-html/unnamed-chunk-7-1.png)<!-- --> --- # Base R graphics: sf II ```r plot(st_geometry(nz)) plot(nz_height, add = TRUE) ``` ``` ## Warning in plot.sf(nz_height, add = TRUE): ignoring all but the first ## attribute ``` ```r sf_cols = sf.colors(n = 2, alpha = 0.2) nz$col = factor(x = nz$Island, labels = sf_cols) plot(st_geometry(nz), col = as.character(nz$col)) ``` <div class="figure"> <img src="04_viz_files/figure-html/unnamed-chunk-8-1.png" alt=" " width="40%" /><img src="04_viz_files/figure-html/unnamed-chunk-8-2.png" alt=" " width="40%" /> <p class="caption"> </p> </div> --- # sf graphics: code ```r # facet plots by default plot(nz) # plot just geometry, ready for new layers: plot(st_geometry(nz), reset = FALSE) # addition of new layers plot(nz_height, add = TRUE) # transparency sf_cols = sf.colors(n = 2, alpha = 0.2) nz$col = factor(x = nz$Island, labels = sf_cols) plot(st_geometry(nz), col = as.character(nz$col)) # see ?plot.sf for more ``` -- ## Observations - Facets by default: useful for seeing patterns. - Transparency new, `add = ...` argument the sam.e - You can go far with base R graphics (Murrell, 2016). --- # tmap - A diverse dedicated mapping R package ```r library(tmap) tm_shape(nz) + tm_polygons("Median_income", palette = "RdYlBu") ``` ![](04_viz_files/figure-html/unnamed-chunk-10-1.png)<!-- --> --- # Why tmap? - It is powerful and flexible. - Concise syntax, attractive maps with minimal code, familiar to **ggplot2** users. - Unique capability: same code -> static + interactive maps with switch `tmap_mode()`. - Wide range of spatial classes (including `raster` objects) supported. - Well documented + developed --- see [`tmap-nutshell`](https://cran.r-project.org/web/packages/tmap/vignettes/tmap-nutshell.html) and JSS paper (Tennekes, 2018). -- - It's also at eRum! - At 13:30 in room N15 203: "Plotting spatial data in R". --- # tmap basics ```r # 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() + tm_borders() ``` <div class="figure"> <img src="04_viz_files/figure-html/unnamed-chunk-11-1.png" alt="tmap basics" width="32%" /><img src="04_viz_files/figure-html/unnamed-chunk-11-2.png" alt="tmap basics" width="32%" /><img src="04_viz_files/figure-html/unnamed-chunk-11-3.png" alt="tmap basics" width="32%" /> <p class="caption">tmap basics</p> </div> <!-- --- --> <!-- # tmap objects --> <!-- --- --> <!-- # Aesthetics --> <!-- --- --> <!-- # Layouts --> <!-- --- --> <!-- # Facets --> <!-- --- --> --- # Animations - Are easy with **tmap** (section [9.3](http://geocompr.robinlovelace.net/adv-map.html#animated-maps) of geocompr) <img src="https://user-images.githubusercontent.com/1825120/38543030-5794b6f0-3c9b-11e8-9da9-10ec1f3ea726.gif" width="80%" /> --- # Interactive maps with mapview ```r m = mapview::mapview(nz) m@map ```
--- # Web mapping applications - Leaflet integrates with **shiny** via `leaflet::leafletOutput()`, enabling web mapping applications built on R - These can be set-up to scale nationally, as illustrated by [pct.bike](http://www.pct.bike/) (Lovelace, Goodman, Aldred, Berkoff, Abbas, and Woodcock, 2017). ![](https://raw.githubusercontent.com/npct/pct-team/master/figures/pct-frontpage.png)<!-- --> --- # Exercises 1. Create a map showing the geographic distribution of the Human Development Index (`HDI`) across Africa with -base graphics (hint: use `plot()`) and -**tmap** (hint: use `tm_shape(africa) + ...`). - Name two advantages of each approach - Bonus: What three other mapping packages could be used to show the same data? -- ## Starting point for the exercise: ```r library(sf) library(spData) library(tidyverse) africa = world %>% filter(continent == "Africa", !is.na(iso_a2)) %>% left_join(worldbank_df, by = "iso_a2") %>% select(name, subregion, gdpPercap, HDI, pop_growth) %>% st_transform("+proj=aea +lat_1=20 +lat_2=-23 +lat_0=0 +lon_0=25") ``` --- class: small # References Bivand, Roger S, Edzer Pebesma and Virgilio Gómez-Rubio (2013). _Applied Spatial Data Analysis with R_. 2nd ed. 2013 edition. New York: Springer. 405 pp. ISBN: 978-1-4614-7617-7. Cheng, Joe, Bhaskar Karambelkar and Yihui Xie (2018). _Leaflet: Create Interactive Web Maps with the JavaScript 'Leaflet' Library_. R package version 2.0.0. URL: [https://CRAN.R-project.org/package=leaflet](https://CRAN.R-project.org/package=leaflet). Lovelace, Robin, Anna Goodman, Rachel Aldred, et al. (2017). "The Propensity to Cycle Tool: An Open Source Online System for Sustainable Transport Planning". In: _Journal of Transport and Land Use_ 10.1. ISSN: 1938-7849. DOI: [10.5198/jtlu.2016.862](https://doi.org/10.5198/jtlu.2016.862). URL: [https://www.jtlu.org/index.php/jtlu/article/view/862](https://www.jtlu.org/index.php/jtlu/article/view/862) (visited on Jun. 01, 2017). Lovelace, Robin, Jakub Nowosad and Jannes Meunchow (2018). _Geocomputation with R_. CRC Press. URL: [http://robinlovelace.net/geocompr](http://robinlovelace.net/geocompr) (visited on Oct. 05, 2017). Murrell, Paul (2016). _R Graphics, Second Edition_. CRC Press. 536 pp. ISBN: 978-1-4398-3177-9. Google Books: googlebooks. Talbert, Richard J. A. (2014). _Ancient Perspectives: Maps and Their Place in Mesopotamia, Egypt, Greece, and Rome_. University of Chicago Press. 284 pp. ISBN: 978-0-226-78940-8. Google Books: googlebooks. Tennekes, Martijn (2018). "Tmap: Thematic Maps in R". In: _Journal of Statistical Software, Articles_ 84.6, pp. 1-39. ISSN: 1548-7660. DOI: [10.18637/jss.v084.i06](https://doi.org/10.18637/jss.v084.i06). URL: [https://www.jstatsoft.org/v084/i06](https://www.jstatsoft.org/v084/i06).