0% found this document useful (0 votes)
16 views77 pages

P 2018 Basel Rspatial1

This document provides an overview of spatial data analysis in R, detailing the necessary packages, data structures, and functionalities for handling both vector and raster data. It highlights the evolution of spatial analysis in R, the advantages of using R as a GIS, and includes examples of geoprocessing operations. The tutorial also covers coordinate reference systems and geometric calculations using various R packages.

Uploaded by

Caro55185162
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views77 pages

P 2018 Basel Rspatial1

This document provides an overview of spatial data analysis in R, detailing the necessary packages, data structures, and functionalities for handling both vector and raster data. It highlights the evolution of spatial analysis in R, the advantages of using R as a GIS, and includes examples of geoprocessing operations. The tutorial also covers coordinate reference systems and geometric calculations using various R packages.

Uploaded by

Caro55185162
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Spatial Data in R: Overview and Examples

Earth Observation Workshop, Basel

Michael Dorman
Geography and Environmental Development
dorman@post.bgu.ac.il

2018-02-26 - 2018-03-01
Contents

I The aim of this tutorial is to provide an overview to spatial


analysis in R
I Slides and code available on GitHub
I Data available on Dropbox
Requirements

I Several packages need to be installed to run code examples -

install.packages("rgdal")
install.packages("sf")
install.packages("raster")
install.packages("rgeos")
install.packages("geosphere")
install.packages("rmapshaper")
install.packages("gstat")
install.packages("automap")
install.packages("spdep")
install.packages("spatstat")
install.packages("osmdata")
install.packages("mapview")
Requirements

I Set to working directory with the data -


I cb_2015_us_state_5m - US states (Shapefile)
I us-states.geojson - US states (GeoJSON)
I dem.tif - Digital Elevation Model (GeoTIFF)
Introduction
I R is a programming language and environment, originally
developed for statistical computing and graphics
I Over time, there was an increasing number of contributed
packages for handling and analysing spatial data in R
I Today, spatial analysis is a major functionality in R
I As of November 2017, there are over 180 packages
specifically addressing spatial analysis in R

Figure 1: Books on Spatial Data Analysis with R


History

I pre-2003: Variable and incomplete approaches (MASS,


spatstat, maptools, geoR, splancs, gstat, . . . )
I 2003: Concensus that a package with base classes should be
useful; rgdal released on CRAN
I 2005: sp released on CRAN; sp support in rgdal
I 2008: Applied Spatial Data Analysis with R, 1st ed.
I 2010: raster released on CRAN
I 2011: rgeos released on CRAN
I 2013: Applied Spatial Data Analysis with R, 2nd ed.
I 2016: sf released on CRAN
History

Figure 2: The network structure of CRAN1 ; sp ecosystem shown in green

1
blog.revolutionanalytics.com/2015/07/the-network-structure-of-cran.html
R as a GIS?

I Strengths of R as a GIS
I R capabilities in data processing and visualization, combined
with dedicated packages for spatial data
I A single environment encompassing all analysis aspects -
acquiring data, computation, statistics, visualization, Web, etc.
I General advantages of programming
I Automation - Doing otherwise unfeasible repetitive tasks
I Reproducibility - Precise control of instructions to the
computer
I Situations when other tools are needed
I Interactive editing or georeferencing (but see mapedit)
I Unique GIS algorithms (label placement, network routing,
splitting lines at intersections, etc.)
I Data that cannot fit in RAM (but R can connect to spatial
databases)
Notable packages

I Handling spatial data


I sp, rgdal, rgeos, sf, raster
I Geometry
I geosphere, mapshaper
I Statistics
I gstat, automap, spatstat, spdep
I Data access
I osmdata
I Visualization
I ggplot2, ggmap, mapview, leaflet
Vector: Types of data

POINT LINESTRING POLYGON

MULTIPOINT MULTILINESTRING MULTIPOLYGON GEOMETRYCOLLECTION

Figure 3: Vector data types (Simple Features)


Vector: File formats

I Binary
I ESRI Shapefile (.shp, .shx, .dbf, .prj, . . . )
I Plain Text
I GeoJSON (.json or .geojson)
I GPX (.gpx)
I Spatial Databases
I PostGIS / PostgreSQL
Vector: Data structures (sp)

I Package sp has 6 main classes for vector layers


I One for each geometry type (points, lines, polygons)
I One for geometry only and one for geometry with attributes

Table 1: Spatial data structures in package sp

class geometry attributes


SpatialPoints Points -
SpatialPointsDataFrame Points data.frame
SpatialLines Lines -
SpatialLinesDataFrame Lines data.frame
SpatialPolygons Polygons -
SpatialPolygonsDataFrame Polygons data.frame
Vector: Data structures (sf)

I Package sf defines a hierarchical class system


I Class sfg is for a single geometry
I Class sfc is a set of geometries with a CRS
I Class sf is a layer with attributes

Table 2: Spatial data structures in package sf

class hierarchy data


sfg geometry coords, type, dimension
sfc geometry column Set of sfg + CRS
sf layer sfc + attributes
Raster: Types of data

Figure 4: Raster data types2

2
http://neondataskills.org/R/Introduction-to-Raster-Data-In-R/
Raster: File formats

I “Simple” rasters
I GeoTiff (.tif)
I Erdas Imagine Image (.img)
I “Complex” rasters (>3D and / or metadata)
I HDF (.hdf)
I NetCDF (.nc)
Raster: Data structures

I The raster package defines 3 classes for raster data


I RasterLayer for single-band
I RasterStack and RasterBrick for multi-band

Table 3: Spatial data structures in package raster

class layers storage


RasterLayer 1 Disk or RAM
RasterStack >=1 Disk and/or RAM
RasterBrick >=1 Disk (single file) or RAM
Input and output of spatial data

I Reading spatial layers from a file into an R data structure, or


writing the R data structure into a file, are handled by external
libraries -
I OGR is used for reading/writing vector files, with rgdal / sp
or sf
I GDAL is used for reading/writing raster files, with raster
I PROJ4 is used for handling CRS, in both rgdal / sp, sf and
raster
I Working with specialized formats, e.g. HDF with gdalUtils
or NetCDF with ncdf4
Coordinate Reference Systems (CRS)

I A Coordinate Reference System (CRS) defines how the


coordinates in the data relate to the surface of the Earth
I Two types of CRS
I Geographic - longitude and latitude, in degrees
I Projected - implying flat surface, associated with measurement
units (e.g. meters)
Coordinate Reference Systems (CRS)

Figure 5: Geographic (WGS 84; left) and projected (NAD83 / UTM zone
12N; right) CRS3

3
https://geocompr.robinlovelace.net/spatial-class.html
Coordinate Reference Systems (CRS)

I In R, CRS are defined using an ESPG code or PROJ.4 string


I Comparing Map Projections
I A table with EPSG code and PROJ.4 strings for all projections
-

crs = rgdal::make_EPSG()
Coordinate Reference Systems (CRS)

I For example, the WGS84 geographic projection can be


defined using its EPSG code

4326

I Or using its PROJ.4 string

"+proj=longlat +datum=WGS84 +no_defs"


rgdal, sf, raster: Handling spatial data

I Function readOGR can be used to read vector layers into sp


data structures -
library(rgdal)

pol_sp = readOGR("data", "cb_2015_us_state_5m")


## OGR data source with driver: ESRI Shapefile
## Source: "data", layer: "cb_2015_us_state_5m"
## with 49 features
## It has 1 fields

class(pol_sp)
## [1] "SpatialPolygonsDataFrame"
## attr(,"package")
## [1] "sp"
rgdal, sf, raster: Handling spatial data

I Function st_read can be used to read vector layers into sf


data structures -
library(sf)

pol_sf = st_read("data/cb_2015_us_state_5m.shp")
## Reading layer `cb_2015_us_state_5m' from data source `/home/michael/Dropbox/
## Simple feature collection with 49 features and 1 field
## geometry type: MULTIPOLYGON
## dimension: XY
## bbox: xmin: -124.7332 ymin: 24.51496 xmax: -66.9499 ymax: 49.38436
## epsg (SRID): 4326
## proj4string: +proj=longlat +datum=WGS84 +no_defs

class(pol_sf)
## [1] "sf" "data.frame"
rgdal, sf, raster: Handling spatial data
I Since sf is new, the majority of the R-Spatial ecosystem only
works with sp
I “Migration” document between sp and sf
I Conversion sp → sf

x = st_as_sf(pol_sp)
class(x)
## [1] "sf" "data.frame"

I Conversion sf → sp

x = as(pol_sf, "Spatial")
class(x)
## [1] "SpatialPolygonsDataFrame"
## attr(,"package")
## [1] "sp"
rgdal, sf, raster: Handling spatial data

I Functions raster, stack and brick can be used to read


single-band rasters into raster data structures -
library(raster)

r = raster("data/dem.tif")
r
## class : RasterLayer
## dimensions : 333, 286, 95238 (nrow, ncol, ncell)
## resolution : 90, 90 (x, y)
## extent : 673414, 699154, 3615239, 3645209 (xmin, xmax, ymin, ymax)
## coord. ref. : +proj=utm +zone=36 +ellps=WGS84 +units=m +no_defs
## data source : /home/michael/Dropbox/Presentations/p_2018_02_EO_Workshop_Base
## names : dem
## values : -12, 537 (min, max)

class(r)
## [1] "RasterLayer"
## attr(,"package")
## [1] "raster"
rgdal, sf, raster: Handling spatial data
I CRS of sp vector layer

proj4string(pol_sp)
## [1] "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +t

I CRS of raster layer

proj4string(r)
## [1] "+proj=utm +zone=36 +ellps=WGS84 +units=m +no_defs"

I CRS of sf vector layer

st_crs(pol_sf)
## Coordinate Reference System:
## EPSG: 4326
## proj4string: "+proj=longlat +datum=WGS84 +no_defs"
rgeos, sf: Geoprocessing Vector Layers
I GEOS is used for geometric operations on vector layers with
rgeos / sf -
I Numeric operators - Area, Length, Distance. . .
I Logical operators - Contains, Within, Within distance,
Crosses, Overlaps, Equals, Intersects, Disjoint, Touches. . .
I Geometry generating operators - Centroid, Buffer,
Intersection, Union, Difference, Convex-Hull, Simplification. . .
width: −0.2 width: 0 width: 0.2

width: −0.2 width: 0 width: 0.2

Figure 6: Buffer function


rgeos, sf: Geoprocessing Vector Layers

I Distance using package rgeos

library(rgeos)

gDistance(pol_sp[1, ], pol_sp[2, ], byid = TRUE)


## 0
## 1 20.57536

I Distance using package sf

st_distance(pol_sf[1, ], pol_sf[2, ])
## Units: m
## [,1]
## [1,] 1888200
raster: Geoprocessing Rasters

I Geometric operations on rasters can be done with package


raster -
I Accessing cell values - As vector, As matrix, Extract to points
/ lines / polygons, random / regular sampling, Frequency table,
Histogram. . .
I Raster algebra - Arthmetic (+, -, . . . ), Math (sqrt, log10,
. . . ), logical (!, ==, >, . . . ), summary (mean, max, . . . ), Mask,
Overlay. . .
I Changing resolution and extent - Crop, Mosaic,
(Dis)aggregation, Reprojection, Resampling, Shift, Rotation. . .
I Focal operators - Distance, Direction, Focal Filter, Slope,
Aspect, Flow direction. . .
I Transformations - Vector layers <-> Raster. . .
raster: Geoprocessing Rasters
slope_asp = terrain(
r,
opt = c("slope", "aspect"),
unit = "degrees"
)

Elevation (m) Slope (°) Aspect (°)

500 350
40
300
400
50 30 250
300 200
20
0

20
150

150
10

200
0
35

300 100
0

100 10
50
50

45
250 0 0 0 0
40
0

Figure 7: Topographic aspect and slope calculation


geosphere: Geometric calculations on longitude/latitude
I Package geosphere implements spherical trigonometry
functions for distance and direction-related calculations on
geographic coordinates (lon-lat)
100
50

*
Latitude

0
−50
−100

−150 −100 −50 0 50 100 150

Longitude

Figure 8: Points on Great Circle


geosphere: Geometric calculations on longitude/latitude

Figure 9: Visualizing Facebook Friends with geosphere4

4
http://paulbutler.org/archives/visualizing-facebook-friends/
geosphere: Example

library(geosphere)

LA = c(-118.40, 33.95)
NY = c(-73.78, 40.63)
gci = gcIntermediate(LA, NY)

head(gci)
## lon lat
## [1,] -117.6264 34.23369
## [2,] -116.8477 34.51250
## [3,] -116.0638 34.78633
## [4,] -115.2747 35.05510
## [5,] -114.4804 35.31872
## [6,] -113.6810 35.57712
rmapshaper
I rmapshaper is an R wrapper around the mapshaper tool,
which also has a nice web-interface
I The main advantage of rmapshaper is the topologically-aware
simplification algorithm (also see Vignette)
I Shared boundaries between polygons are always kept intact,
with no gaps or overlaps

library(rmapshaper)
pol_sp_s1 = ms_simplify(pol_sp, keep = 0.05)
pol_sp_s2 = ms_simplify(pol_sp, keep = 0.01)

Figure 10: Original (left), 0.05 points retained (middle) and 0.01 retained
(right)
gstat: Geostatistical Modelling
I Univariate and multivariate geostatistics -
I Variogram modelling
I Ordinary and universal point or block (co)kriging
I Cross-validation

333000

7.0
332000

6.5

6.0
331000

5.5

5.0
330000

178500 179500 180500 181500

Figure 11: Predicted Zinc concentration, using Ordinary Kriging


gstat: Example
I Preparing input data

library(gstat)
library(automap)

data(meuse)
data(meuse.riv)
coordinates(meuse) = ~ x + y
data(meuse.grid)
gridded(meuse.grid) = ~ x + y
grid = raster(meuse.grid)
grid[!is.na(grid)] = 1

I Plot

plot(grid)
plot(meuse, add = TRUE)
gstat: Example

333000
1.0010
332000

1.0005

1.0000
331000

0.9995

0.9990
330000

178500 179500 180500 181500

Figure 12: Area of interest and point measurements


gstat: Example

I Function autofitVariogram in package automap provides an


automatic variogram model fitting procedure

v = autofitVariogram(log(zinc) ~ 1, meuse)

v$var_model
## model psill range
## 1 Nug 0.04848089 0.0000
## 2 Sph 0.58754741 889.9084
gstat: Example
I The fitted variogram model is shown below -

plot(v)

Experimental variogram and fitted variogram model

1314
1139
0.6 1349 1355
0.5 830
Semi−variance

0.4
711
0.3
149
184
0.2
36114
Model: Sph

0.1 17 Nugget: 0.05


Sill: 0.64
Range: 890

500 1000 1500

Distance

Figure 13: Fitted variogram model


gstat: Example

I Function gstat creates a geostatistical model object (class


gstat)
I The object holds all necessary information for making
predictions -
I The model definition (formula, model)
I The calibration data (data)

g = gstat(
formula = log(zinc) ~ 1,
model = v$var_model,
data = meuse
)
gstat: Example

I Interpolation requires the geostatistical model and the new


locations -

predicted = interpolate(grid, g)
## [using ordinary kriging]

I Plotting the result -

plot(predicted)
contour(predicted, add = TRUE)
gstat: Example
7

333000
6.8

6.4
6.2
7
7.2

7.4
332000 7.0
6.8 6.4 5.2
6
5.6 6.5

7
6.0
331000

5
5.5
7
6.6 5.4 5.0
5.8
6
6.2
6.6

6.8
330000

6.2 5.2
6.4
6.4 6 6.2

178500 179500 180500 181500

Figure 14: Predicted Zinc concentration, using Ordinary Kriging


gstat: Example

I We are usually interested in predictions within an area of


interest rather than the entire rectangular extent of the
“template” raster
I The mask function can be used to “erase” the irrelevant area

predicted = mask(predicted, grid)


gstat: Example

6
6.

6.8
333000

4
5.
4
6.
7.0

7
332000
6.8 5.2
6
6.6 5.6 6.5

6.0
331000

5.5
5
6.4
8
6.

5.6 5.4 5.0


6.6
6
6.2 6.2
5.8

6.4
6.6
330000

6
6.2 5.2

6.4 5.8

178500 179500 180500 181500

Figure 15: Predicted Zinc concentration, using Ordinary Kriging


spdep: Spatial dependence modelling

I Modelling with spatial weights -


I Building neighbour lists and spatial weights
I Tests for spatial autocorrelation for areal data (e.g. Moran’s I)
I Spatial regression models (e.g. SAR, CAR)

Figure 16: Neighbours list based on regions with contiguous boundaries


spdep: Example

I Loading the North Carolina dataset, see ?spData::nc.sids

file = system.file("shape/nc.shp", package = "sf")


nc = st_read(file)

I Calculating Sudden Infant Death (SID) rate

nc$rate = nc$SID79 / nc$BIR79


spdep: Example
plot(nc[, "rate"])

rate

0.006
0.004
0.002
0.000
Figure 17: SIDS rate in North Carolina
spdep: Example

I Creating spatial weights is a necessary step in using areal


data -
I Defining which areas are concidered “neighbors”
I Assigning weights to the identified neighbor links
I A common approach is to give a weight of 1/n to all n areas
that share a common boundary with given focal area, and 0 to
all other areas
I Function poly2nb can be used to define the neighbors -

library(spdep)
nc = as(nc, "Spatial")
nb = poly2nb(nc)
spdep: Example

summary(nb)
## Neighbour list object:
## Number of regions: 100
## Number of nonzero links: 490
## Percentage nonzero weights: 4.9
## Average number of links: 4.9
## Link number distribution:
##
## 2 3 4 5 6 7 8 9
## 8 15 17 23 19 14 2 2
## 8 least connected regions:
## 4 21 45 56 77 80 90 99 with 2 links
## 2 most connected regions:
## 39 67 with 9 links
spdep: Example

plot(nc, border = "grey")


plot(nb, coordinates(nc), add = TRUE, col = "black")

Figure 18: Neighbours list based on regions with contiguous boundaries


spdep: Example

I Then function nb2listw can then be used to calculate the


neighbor weights -

nbw = nb2listw(nb)
spdep: Example

summary(nbw)
## Characteristics of weights list object:
## Neighbour list object:
## Number of regions: 100
## Number of nonzero links: 490
## Percentage nonzero weights: 4.9
## Average number of links: 4.9
## Link number distribution:
##
## 2 3 4 5 6 7 8 9
## 8 15 17 23 19 14 2 2
## 8 least connected regions:
## 4 21 45 56 77 80 90 99 with 2 links
## 2 most connected regions:
## 39 67 with 9 links
##
## Weights style: W
## Weights constants summary:
## n nn S0 S1 S2
## W 100 10000 100 44.65023 410.4746
spdep: Example
I Moran’s I is the most common global test for spatial
auto-correlation
I Values of I range from −1 to +1, with the expected value
being −1/(N − 1)
I Low values indicate negative spatial autocorrelation
I High values indicate positive spatial autocorrelation
moran.test(nc$rate, nbw)
##
## Moran I test under randomisation
##
## data: nc$rate
## weights: nbw
##
## Moran I statistic standard deviate = 2.3625, p-value = 0.009075
## alternative hypothesis: greater
## sample estimates:
## Moran I statistic Expectation Variance
## 0.142750422 -0.010101010 0.004185853
Disease mapping

Figure 19: Chapter 10 Disease Mapping, in Bivand et al. 2013


spatstat: Spatial point pattern analysis
I Techniques for statistical analysis of spatial point patterns,
such as -
I Kernel density estimation
I Detection of clustering using Ripley’s K-function
I Spatial logistic regression

0.1 0.14

0.0
4
0.2

0.1

6
0.06

6
0.04 0.1

0.0
0.16
0.04 0.04 0.16
0.06 0.12
2 0.08
0.1 0.06
0.04 0.06
0.1 0.1 0.08
0.04 0.04
0.06 0.04
0.04
0.08
0.06 0.08 0.06
0.04 0.04 0.04 0.06

2
0.1
0.08 0.04
0.04 0.04
0.12 0.06

0.1
0.14

0.06
0.04 0.06
0.06 0.04

0.1
0.04

0.04 0.08 0.04 0.0


0.04 4
0.1 0.04 0.04 0.08 0.06 0.04
0.08
0.06
0.04 0.04
0.04 0.06
0.04 0.06
0.06
0.06 0.04 0.06 0.08 0.06
0.08 0.06
0.08 0.04
0.1

0.06 0.04 0.04


0.04
0.06 0.04
0.04
0.08 0.1
0.06 0.04
0.1
0.06
0.04 0.08
0.06

0.14
0.1 0.04
0.04 0.04 6
0.04
0.0

2
0.1 0.14 0.12
0.1
6
0.06

0.0

6
0.1
0.18 0.08
6

Figure 20: Distance map for the Biological Cells Point Pattern dataset
spatstat: Example

I The spatstat package comes with several sample datasets,


including -
I cells - Biological Cells Point Pattern
I japanesepines - Japanese Pines Point Pattern
I redwood - California Redwoods Point Pattern

library(spatstat)
cells
## Planar point pattern: 42 points
## window: rectangle = [0, 1] x [0, 1] units
japanesepines
## Planar point pattern: 65 points
## window: rectangle = [0, 1] x [0, 1] units (one unit = 5.7 metres)
redwood
## Planar point pattern: 62 points
## window: rectangle = [0, 1] x [-1, 0] units
spatstat: Example

plot(cells)
plot(japanesepines)
plot(redwood)

cells japanesepines redwood

Figure 21: Distance map for the Biological Cells Point Pattern dataset
spatstat: Example
I Ripley’s K-function measures the expected number of
random points within a distance r of a typical random point of
a point pattern X

r = seq(0, sqrt(2)/6, by = 0.005)


Kcells = envelope(
cells,
fun = Kest,
r = r,
nsim = 99
)
## Generating 99 simulations of CSR ...
## 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1
## 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
## 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
##
## Done.
spatstat: Example

Kpines = envelope(
japanesepines,
fun = Kest,
r = r,
nsim = 99
)
Kredwood = envelope(
redwood,
fun = Kest,
r = r,
nsim = 99
)
spatstat: Example
plot(Kcells)
plot(Kpines)
plot(Kredwood)

Kcells Kpines Kredwood

0.20

0.20
0.20

K ob s (r ) K ob s (r ) K ob s (r )
^ ^ ^

K t h eo (r ) K t h eo (r ) K t h eo (r )
0.15
K h i (r ) K h i (r ) K h i (r )
^ ^ ^

0.15
0.15

K l o (r ) K l o (r ) K l o (r )
^ ^ ^
0.10
K (r )

K (r )

K (r )

0.10
0.10

0.05

0.05
0.05
0.00

0.00

0.00
0.00 0.05 0.10 0.15 0.20 0.00 0.05 0.10 0.15 0.20 0.00 0.05 0.10 0.15 0.20

r r (one unit = 5.7 metres) r

Figure 22: Distance map for the Biological Cells Point Pattern dataset
osmdata: Access to OpenStreetMap data
I Accessing OpenStreetMap (OSM) data using the Overpass API

library(osmdata)

q = opq(bbox = "Beer-Sheva, Israel")


q = add_osm_feature(q, key = "highway")
dat = osmdata_sf(q)
lines = dat$osm_lines
pol = dat$osm_polygons
pol = st_cast(pol, "MULTILINESTRING")
pol = st_cast(pol, "LINESTRING")
lines = rbind(lines, pol)
lines = lines[, c("osm_id", "highway")]
lines = st_transform(lines, 32636)

plot(lines)
osmdata: Access to OpenStreetMap data

osm_id highway

Figure 23: Beer-Sheva road network


ggplot2, ggmap: Visualization

Figure 24: London cycle hire journeys with ggplot25

5
http://spatial.ly/2012/02/great-maps-ggplot2/
ggplot2, ggmap: Visualization

Figure 25: Crime density by day with ggplot26

6
http://spatial.ly/2012/02/great-maps-ggplot2/
leaflet, mapview: Web mapping

I Packages leaflet and mapview provide methods to produce


interactive maps using the Leaflet JavaScript library
I Package leaflet gives more low-level control
I Package mapview is a wrapper around leaflet, automating
addition of useful features -
I Commonly used basemaps
I Color scales and legends
I Labels
I Popups
mapview: Example

I Function mapview produces an interactive map given a spatial


object
I zcol="..." specifies the attribute used for symbology
I legend=TRUE adds a legend

library(mapview)

states = st_read("data/us-states.geojson")

mapview(states, zcol = "density", legend = TRUE)


mapview: Example

Figure 26: Intractive mapview map


leaflet: Example
I The leaflet package can be used to produce similar
interactive maps, but with finer control
I Defining a color scale function with colorBin

pal = colorBin(
palette = "YlOrRd",
domain = states$density,
bins = c(0, 10, 20, 50, 100, 200, 500, 1000, Inf)
)

I The color scale function accepts a numeric value and returns


a color code -

pal(153)
## [1] "#FD8D3C"
leaflet: Example

I Creating HTML popups

labels = paste0(
"<b>",
states$name,
"</b><br/>",
format(round(states$density, 2), nsmall = 2),
" people / mi<sup>2</sup>"
) %>%
lapply(htmltools::HTML)
leaflet: Example

I Initiating map object with leaflet


I Setting initial extent with setView
I Adding tile layer with addProviderTiles

leaflet(states) %>%
setView(-96, 37.8, 4) %>%
addProviderTiles("CartoDB.DarkMatterNoLabels") %>%
leaflet: Example
I Adding polygonal layer with addPolygons
addPolygons(
fillColor = ~pal(density),
weight = 2,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7,
highlight = highlightOptions(
weight = 5,
color = "#666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE
),
label = labels,
labelOptions = labelOptions(
style = list("font-weight" = "normal", padding = "3px 8px"),
textsize = "15px",
direction = "auto"
)
) %>%
leaflet: Example

I Adding legend with addLegend

addLegend(
pal = pal,
values = ~density,
opacity = 0.7,
title = NULL,
position = "bottomright"
)
leaflet: Example

Figure 27: Intractive leaflet map


Other useful packages

I Geometry
I maptools, dggridR
I Routing
I gdistance, stplanr
I Statistics
I dbscan, gwrr, geoR, nlme, FRK
I Visualization
I rasterVis
I Web APIs
I ggmap
Books
I Hierarchical Modeling and Analysis for Spatial Data (1st
ed 2003, 2nd ed. 2014)
I Model-based Geostatistics (2007)
I Applied Spatial Data Analysis with R (1st ed. 2008, 2nd
ed. 2013)
I A Practical Guide for Geostatistical Mapping (2009)
I Spatial Data Analysis in Ecology and Agriculture using R
(2012)
I Displaying Time Series, Spatial, and Space-Time Data
with R (2014)
I Learning R for Geospatial Analysis (2014)
I An Introduction to R for Spatial Analysis and Mapping
(2015)
I Spatial Point Patterns: Methodology and Applications
with R (2015)
I Geocomputation with R (2018)7
7
https://geocompr.robinlovelace.net/
Online courses and tutorials

I Courses
I https://mgimond.github.io/Spatial/index.html
I http://adamwilson.us/RDataScience/index.html
I http://geog.uoregon.edu/bartlein/courses/geog490/index.html
I Tutorials
I http://www.nickeubank.com/gis-in-r/
I http://neondataskills.org/spatial-data-gis/
Thank you for listening!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy