The R Spatial Ecosystem

“Historical” Packages

  • rgdal: interface between R and GDAL (Geospatial Data Abstraction Library) and PROJ4 libraries: raster / vector geospatial data formats and coordinate transformation.

  • sp: classes and methods for spatial data in R.

  • rgeos: interface between R and GEOS (Geometry Engine - Open Source) library: area, perimeter, distances, dissolve, buffer, overlap, union, contains…

These packages are still widely used.

Simple Features for R

  • sf Website: Simple Features for R

  • First release: October 20, 2016

  • sp, rgeos and rgdal functionalities in one package.

  • Easier data handling, simpler objects.

  • Tidy data: compatibility with the pipe syntax and tidyverse operators.

  • Main author and maintainer: Edzer Pebesma (also sp author)


sf objects data structure:

format sf

Using sf

Data Import

Reading layer `martinique' from data source `C:\Users\Kim Antunez\Desktop\satRdays\satRday\lecture\data\mtq\martinique.shp' using driver `ESRI Shapefile'
Simple feature collection with 34 features and 23 fields
geometry type:  POLYGON
dimension:      XY
bbox:           xmin: 690574.4 ymin: 1592426 xmax: 736126.5 ymax: 1645660
epsg (SRID):    32620
proj4string:    +proj=utm +zone=20 +datum=WGS84 +units=m +no_defs

Projection

Get current crs with st_crs() (epsg code) and change projection with st_transform().

Coordinate Reference System:
  EPSG: 32620 
  proj4string: "+proj=utm +zone=20 +datum=WGS84 +units=m +no_defs"

Data Display

Default plot

Only geometry

Distance Matrix

Units: [m]
          [,1]     [,2]      [,3]      [,4]      [,5]
[1,]     0.000 35297.56  3091.501 12131.617 17136.310
[2,] 35297.557     0.00 38332.602 25518.913 18605.249
[3,]  3091.501 38332.60     0.000 15094.702 20226.198
[4,] 12131.617 25518.91 15094.702     0.000  7177.011
[5,] 17136.310 18605.25 20226.198  7177.011     0.000

Other Packages

CRAN task views aim to provide some guidance which packages on CRAN are relevant for tasks related to a certain topic.

CRAN Task View: Analysis of Spatial Data:

  • Classes for spatial data
  • Handling spatial data
  • Reading and writing spatial data
  • Visualisation
  • Point pattern analysis
  • Geostatistics
  • Disease mapping and areal data analysis
  • Spatial regression
  • Ecological analysis

Maps with R

Overview

Several solutions are available:

  • ggplot2 users can have a look to ggplot2 mapping features (geom_sf) that can mix nicely with ggspatial.
  • For more advanced mapping features in a ggplot2-like syntax have a look to tmap
  • cartography is based on base graphics and allow most of basic and advanced cartographic representations.
    Full disclosure: one of the speakers is the maintainer of cartography.
  • mapview, leaflet and mapdeck for interactive webmaps.

Here we will focus on cartography and do small examples with ggplot2, tmap, leaflet and mapview.

Light Introduction to Graphical Semiology

Light Semiology

Data Preparation

Simple feature collection with 6 features and 16 fields
geometry type:  MULTIPOLYGON
dimension:      XY
bbox:           xmin: 526897.2 ymin: 6922528 xmax: 565312.9 ymax: 6976233
epsg (SRID):    2154
proj4string:    +proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
  INSEE_COM               LIBELLE agr art cad int emp ouv  act pagr  part
1     76001 Allouville-Bellefosse   0  35  30  90 130 125  410 0.00  8.54
2     76002              Alvimare   0  13   8  55  55  72  203 0.00  6.40
3     76004           Ambrumesnil   4  16  12  59  55  47  193 2.07  8.29
4     76005 Amfreville-La-Mi-Voie   0  63 151 434 400 250 1298 0.00  4.85
   pcad  pint  pemp  pouv cat                       geometry
1  7.32 21.95 31.71 30.49 emp MULTIPOLYGON (((528381.5 69...
2  3.94 27.09 27.09 35.47 ouv MULTIPOLYGON (((528381.5 69...
3  6.22 30.57 28.50 24.35 int MULTIPOLYGON (((553154.2 69...
4 11.63 33.44 30.82 19.26 int MULTIPOLYGON (((563304.4 69...
 [ getOption("max.print") est atteint -- 2 lignes omises ]

osmdata allows to extract features from the free and open-source OpenStreetMap database.

cartography

Choropleth Map

We could create the same map on a cartogram based on the active population stock.

Gridded Map

It is also possible to create hexagonal grids.

Smoothed Map

smoothLayer() uses functions from package SpatialPosition to compute Stewart’s potentials of population.
The computation of potentials could be considered as a spatial interpolation method such as inverse distance weighted interpolation (IDW) or kernel density estimator. These models aim to estimate unknown values of non-observed points from known values given by measured points. Cartographically speaking, they are often used to get a continuous surface from a set of discrete points.

Resources

  • A cheat sheet displays a quick overview of cartography’s main features:
    cartography cheat sheet

  • A vignette introduces the package and provides examples of how to create some thematic maps:
    cartography vignette

  • A website shows the package documentation and vignette:
    cartography website

ggplot2 and tmap

ggplot2

Proportional symbols map

Choropleth map

mapview and leaflet

Proportional symbols layer

These interactive maps, as appealing as they seem to be, are not really suitable for presenting geostatistical information.

For proportional symbols both leaflet and mapview lack a proper way to build legends. Nonetheless, they can be really useful for exploratory data analysis.

Both librairies are quite similar with some advantage for mapview (e.g the possibility to render to canvas for bigger datasets) and some other for leaflet (e.g using a customized projection different from web-mercator).

Two other packages mapdeck and leafgl deserve attention since they enable mapdrawing in webgl and therefore can be used with large datasets. They are not introduced here but keep them in mind if needed.

With leaflet data must be provided in long/lat (st_transform(4326)) and will be converted by default to the webmercator coordinate reference system (CRS).

You may choose between circles with radius specified in meters (addCircle) or in pixels (addCircleMarkers). If specified in pixel, the radius will stay the same whatever the zoom level is. If specified in meters, it will evolve with zoom level.

Gridded Map

mapview and leaflet enable the use and styling of sf polygons. We may for example reuse the grid built previously to show the share of managers in Seine-Maritime.

Default choropleth can be obtained with just three arguments with mapview.

leaflet enables fine tuning of the color scale and legend.

Projection

leaflet enables to use other projections than the web-mercator projection for webmaps. You may deal with tiles built with another projection system such as Lambert 93 by defining a custom leaflet crs (see gis.stackexchange resolution-from-wmts-getcapacilities-scaledenomin and mathematics-behind-converting-scale-to-resolution to deal with WMTS tiles).

We use this approach here to deal with Hypsometric tints tiles (tiles colors which encode elevation) and the contour lines of chamois and ibex population area provided by the french national office of hunting and wild animals.

reproducibility

Presentation made with rmdformats package.

Always share your R and packages configuration!

R version 3.5.1 (2018-07-02)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17134)

Matrix products: default

locale:
[1] LC_COLLATE=French_France.1252  LC_CTYPE=French_France.1252   
[3] LC_MONETARY=French_France.1252 LC_NUMERIC=C                  
[5] LC_TIME=French_France.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] tmap_2.2              leaflet_2.0.2         mapview_2.6.3        
 [4] ggplot2_3.1.0         SpatialPosition_1.2.0 raster_2.8-4         
 [7] sp_1.3-1              cartogram_0.1.1       cartography_2.2.0    
[10] bindrcpp_0.2.2        dplyr_0.7.6           sf_0.7-2             
[13] rmdformats_0.3.5      knitr_1.21           

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.17       lattice_0.20-35    png_0.1-7         
 [4] class_7.3-14       assertthat_0.2.0   digest_0.6.15     
 [7] mime_0.6           R6_2.2.2           plyr_1.8.4        
[10] stats4_3.5.1       evaluate_0.12      e1071_1.6-8       
[13] highr_0.7          pillar_1.2.3       rlang_0.3.1       
[16] lazyeval_0.2.1     rstudioapi_0.7     miniUI_0.1.1.1    
[19] rmarkdown_1.11.3   labeling_0.3       webshot_0.5.0     
[22] rgdal_1.3-6        stringr_1.3.1      questionr_0.7.0   
[25] htmlwidgets_1.2    munsell_0.5.0      shiny_1.1.0       
[28] compiler_3.5.1     httpuv_1.4.4.1     xfun_0.3          
[31] tmaptools_2.0-1    pkgconfig_2.0.1    base64enc_0.1-3   
[34] rgeos_0.4-2        htmltools_0.3.6    tidyselect_0.2.5  
[37] tibble_1.4.2       bookdown_0.9       codetools_0.2-15  
[40] XML_3.98-1.12      viridisLite_0.3.0  withr_2.1.2       
[43] later_0.7.3        grid_3.5.1         jsonlite_1.6      
[46] lwgeom_0.1-4       satellite_1.0.1    spData_0.3.0      
[49] xtable_1.8-2       gtable_0.2.0       DBI_1.0.0         
[52] magrittr_1.5       units_0.6-2        scales_1.0.0      
[55] KernSmooth_2.23-15 stringi_1.1.7      promises_1.0.1    
[58] RColorBrewer_1.1-2 tools_3.5.1        dichromat_2.0-0   
[61] glue_1.3.0         purrr_0.2.5        crosstalk_1.0.0   
[64] yaml_2.2.0         colorspace_1.3-2   classInt_0.2-3    
[67] bindr_0.1.1