Required current contributed CRAN packages:

I am running R 3.6.1, with recent update.packages().

needed <- c("mapview", "ggplot2", "cartography", "tmap", "colorspace", "RColorBrewer", "sf", "classInt")

Script

Script and data at https://github.com/rsbivand/ECS530_h19/raw/master/ECS530_IV.zip. Download to suitable location, unzip and use as basis.

Schedule

  • 2/12 (I) Spatial data representation, (II) Support+topology, input/output

  • 3/12 (III) Coordinate reference systems, (IV) Visualization

  • 4/12 (V) R/GIS interfaces, project surgery

  • 5/12 (VI) Spatial autocorrelation, (VII) Spatial regression

  • 6/12 (VIII) Interpolation, point processes, project surgery

  • 7/12 Presentations

Session IV

  • 13:15-13:45 Class intervals

  • 13:45-14:30 Thematic mapping

  • 14:30-15:00 Interactive mapping

Class intervals

classInt provides the key class interval determination for thematic mapping of continuous variables. The classIntervals() function takes a numeric vector (now also of classes POSIXt or units), a target number of intervals, and a style of class interval. Other arguments control the closure and precision of the intervals found.

library(classInt)
args(classIntervals)
## function (var, n, style = "quantile", rtimes = 3, ..., intervalClosure = c("left", 
##     "right"), dataPrecision = NULL, warnSmallN = TRUE, warnLargeN = TRUE, 
##     largeN = 3000L, samp_prop = 0.1, gr = c("[", "]")) 
## NULL

Lapa et al. (2001) (Leprosy surveillance in Olinda, Brazil, using spatial analysis techniques) made available the underlying data set of Olinda census tracts (setor) in the Corrego Alegre 1970-72 / UTM zone 25S projection (EPSG:22525). Marilia Sá Carvalho and I wrote a tutorial in 2003/4 based on this data set; there is more information in the tutorial.

We’ll find 7 intervals using Fisher natural breaks for the deprivation variable:

library(sf)
## Linking to GEOS 3.8.0, GDAL 3.0.2, PROJ 6.2.1
olinda_sirgas2000 <- st_read("olinda_sirgas2000.gpkg")
## Reading layer `olinda_sirgas2000' from data source `/home/rsb/und/ecs530/h19/olinda_sirgas2000.gpkg' using driver `GPKG'
## Simple feature collection with 243 features and 10 fields
## geometry type:  POLYGON
## dimension:      XY
## bbox:           xmin: 288984.5 ymin: 9111038 xmax: 298474.8 ymax: 9120522
## epsg (SRID):    NA
## proj4string:    +proj=utm +zone=25 +south +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
(cI <- classIntervals(olinda_sirgas2000$DEPRIV, n=7, style="fisher"))
## style: fisher
##      [0,0.1215)  [0.1215,0.244)   [0.244,0.339)   [0.339,0.439)  [0.439,0.5435) 
##              37              53              37              26              37 
## [0.5435,0.6695)  [0.6695,0.907] 
##              33              20

We also need to assign a palette of graphical values, most often colours, to use to fill the intervals, and can inspect the intervals and fill colours with a plot method:

The RColorBrewer package gives by permission access to the ColorBrewer palettes accesible from the ColorBrewer website. Note that ColorBrewer limits the number of classes tightly, only 3–9 sequential classes

library(RColorBrewer)
pal <- RColorBrewer::brewer.pal((length(cI$brks)-1), "Reds")
plot(cI, pal)

We can also display all the ColorBrewer palettes:

display.brewer.all()

Try exploring alternative class interval definitions and palettes, maybe also visiting http://hclwizard.org/ and its hclwizard() Shiny app, returning a palette generating function on clicking the “Return to R” button:

library(colorspace)
hcl_palettes("sequential (single-hue)", n = 7, plot = TRUE)

pal <- hclwizard()
pal(6)

The end of rainbow discussion is informative:

wheel <- function(col, radius = 1, ...)
  pie(rep(1, length(col)), col = col, radius = radius, ...) 
opar <- par(mfrow=c(1,2))
wheel(rainbow_hcl(12))
wheel(rainbow(12))

par(opar)

See recent R blog.

See also treatments in Fundamentals of Data Visualization.

Thematic mapping

The sp package provided base graphics plot and image methods. sf provides plot methods using base graphics; the method for "sf" objects re-arranges the plot window to provide a colour key, so extra steps are needed if overplotting is needed:

plot(olinda_sirgas2000[,"DEPRIV"], breaks=cI$brks, pal=pal)

(returns current par() settings); the method also supports direct use of classInt:

plot(olinda_sirgas2000[,"DEPRIV"], nbreaks=7, breaks="fisher", pal=pal)

Earlier we used the plot method for "sfc" objects which does not manipulate the graphics device, and is easier for overplotting.

The tmap package

tmap: Thematic maps show spatial distributions. The theme refers to the phenomena that is shown, which is often demographical, social, cultural, or economic. The best known thematic map type is the choropleth, in which regions are colored according to the distribution of a data variable. The R package tmap offers a coherent plotting system for thematic maps that is based on the layered grammar of graphics. Thematic maps are created by stacking layers, where per layer, data can be mapped to one or more aesthetics. It is also possible to generate small multiples. Thematic maps can be further embellished by configuring the map layout and by adding map attributes, such as a scale bar and a compass. Besides plotting thematic maps on the graphics device, they can also be made interactive as an HTML widget. In addition, the R package tmaptools contains several convenient functions for reading and processing spatial data. See (Tennekes 2018) and Chapter 8 in (Lovelace, Nowosad, and Muenchow 2019).

The tmap package provides cartographically informed, grammar of graphics (gg) based functionality now, like ggplot2 using grid graphics. John McIntosh tried with ggplot2, with quite nice results. I suggested he look at tmap, and things got better, because tmap can switch between interactive and static viewing. tmap also provides direct access to classInt class intervals.

library(tmap)
tmap_mode("plot")
## tmap mode set to plotting
o <- tm_shape(olinda_sirgas2000) + tm_fill("DEPRIV", style="fisher", n=7, palette="Reds")
class(o)
## [1] "tmap"

returns a "tmap" object, a grid GROB (graphics object), with print methods.

o

Since the objects are GROBs, they can be updated, as in lattice with latticeExtra or ggplot2:

o + tm_borders(alpha=0.5, lwd=0.5)

There is also a Shiny tool for exploring palettes:

tmaptools::palette_explorer()

The cartography package

cartography helps to design cartographic representations such as proportional symbols, choropleth, typology, flows or discontinuities maps. It also offers several features that improve the graphic presentation of maps, for instance, map palettes, layout elements (scale, north arrow, title…), labels or legends. (Giraud and Lambert 2016, 2017), http://riatelab.github.io/cartography/vignettes/cheatsheet/cartography_cheatsheet.pdf. The package is associated with rosm: Download and plot Open Street Map http://www.openstreetmap.org/, Bing Maps http://www.bing.com/maps and other tiled map sources. Use to create basemaps quickly and add hillshade to vector-based maps. https://cran.r-project.org/web/packages/rosm/vignettes/rosm.html

The package organizes extra palettes:

library(cartography)
display.carto.all()

The plotting functions (mot methods) use base graphics:

choroLayer(olinda_sirgas2000, var="DEPRIV", method="fisher-jenks", nclass=7, col=pal, legend.values.rnd=3)

(returns NULL)

The ggplot2 package

The ggplot2 package provides the geom_sf() facility for mapping:

library(ggplot2)
g <- ggplot(olinda_sirgas2000) + geom_sf(aes(fill=DEPRIV))
g

It is possible to set a theme that drops the arguably unnecessary graticule:

g + theme_void()

g + theme_void() + scale_fill_distiller(palette="Reds", direction=1)

but there is a lot of jumping through hoops to get a simple map. To get proper class intervals involves even more work, because ggplot2 takes specific, not general, positions on how graphics are observed. ColorBrewer eschews continuous colour scales based on cognitive research, but ggplot2 enforces them for continuous variables (similarly for graticules, which may make sense for data plots but not for maps).

Interactive maps

tmap modes

Using tmap_mode(), we can switch between presentation ("plot") and interactive ("view") plotting:

tmap_mode("view")
## tmap mode set to interactive viewing
o + tm_borders(alpha=0.5, lwd=0.5)
tmap_mode("plot")
## tmap mode set to plotting

There is also a Shiny tool for exploring palettes:

tmaptools::palette_explorer()

The **mapview* package

mapview: Quickly and conveniently create interactive visualisations of spatial data with or without background maps. Attributes of displayed features are fully queryable via pop-up windows. Additional functionality includes methods to visualise true- and false-color raster images, bounding boxes, small multiples and 3D raster data cubes. It uses leaflet and other HTML packages.

library(mapview)
mapview(olinda_sirgas2000, zcol="DEPRIV", col.regions=pal, at=cI$brks)

Further examples

data("pol_pres15", package = "spDataLarge")
pol_pres15 <- st_buffer(pol_pres15, dist=0)
library(tmap)
o <- tm_shape(pol_pres15) + tm_facets(free.scales=FALSE) + tm_borders(lwd=0.5, alpha=0.4) + tm_layout(panel.labels=c("Duda", "Komorowski"))
o + tm_fill(c("I_Duda_share", "I_Komorowski_share"), n=6, style="pretty", title="I round\nshare of votes")

o + tm_fill(c("II_Duda_share", "II_Komorowski_share"), n=6, style="pretty", title="II round\nshare of votes")

Giraud, Timothée, and Nicolas Lambert. 2016. “cartography: Create and Integrate Maps in Your R Workflow.” Journal of Open Source Software 1 (4). https://doi.org/10.21105/joss.00054.

———. 2017. “Reproducible Cartography.” In Advances in Cartography and Giscience. ICACI 2017. Lecture Notes in Geoinformation and Cartography, edited by Michael Peterson, 173–83. Cham, Switzerland: Springer. https://doi.org/10.1007/978-3-319-57336-6\_13.

Lapa, Tiago, Ricardo Ximenes, Nilza Nunes Silva, Wayner Souza, Maria de Fátima Militão Albuquerque, and Gisele Campozana. 2001. “Vigilância da hanseníase em Olinda, Brasil, utilizando técnicas de análise espacial.” Cadernos de Saúde Pública 17 (October): 1153–62. https://doi.org/10.1590/S0102-311X2001000500016.

Lovelace, Robin, Jakub Nowosad, and Jannes Muenchow. 2019. Geocomputation with R. Boca Raton, FL: Chapman and Hall/CRC. https://geocompr.robinlovelace.net/.

Tennekes, Martijn. 2018. “tmap: Thematic Maps in R.” Journal of Statistical Software 84 (6): 1–39. https://www.jstatsoft.org/v084/i06.