# R in Space - Basic mapping

## Plot methods for sp objects

Let’s first get some data:

library(sp)
library(sf)
library(raster)
dir.create("data")
bel1 <- getData("GADM", country = "BEL", level = 1, path = "data/")
bel2 <- getData("GADM", country = "BEL", level = 2, path = "data/")

Quick plot:

plot(bel1)

Two quick plots:

par(mfrow = c(1,2), mar = c(0,0,0,0))
plot(bel1, col = 1:3)
plot(bel2, lty = 2)

Slightly customized plots:

plot(bel1, col = "grey85", main = "Belgium")
plot(bel2, lwd = .5, add = T)
points(coordinates(bel2), pch = 19, cex = .4)
city = coordinates(bel2)[1,]
text(city[1], city[2], labels = "Bruxelles", pos = 3, col = "#9728eb")

## plot methods for sf objects

Let’s first get two sf object:

bel1_sf <- st_as_sf(bel1)
bel2_sf <- st_as_sf(bel2)

Let’s try a simple plot.

plot(bel1_sf)

It actually plots one map per variable and colors the polygon according to the values. To obtain something similar to what is found in sp, an sfc object must be used:

plot(st_geometry(bel1_sf), lwd = 1.5, col = "grey85")
# same as :
# plot(bel1_sf$geometry, lwd = 1.5, col = "grey85") plot(st_geometry(bel2_sf), lwd = .5, add = T) ## plot methods for raster objects Let’s get a raster layer of altitude in Belgium using again getData(). alt <- getData("alt", country = "Belgium", path = "data/") plot(alt) We can also add different layers of information on this maps: plot(alt) contour(alt, add = T) Or reclassify and change the color palette: # Assign color to a object myCol <- terrain.colors(3) plot(alt, breaks = c(0, 200, 400, 700), col = myCol, main = "Altitude map of Belgium") ## plotting together sf and raster objects # Create a new color palette library(RColorBrewer) myPal <- brewer.pal(n = 9, name = "Greens") # Plot the altitude raster plot(alt, col = myPal, xlab = "Longitude", ylab = "Latitude") # Add Belgium boundary map plot(st_geometry(bel2_sf), add = T) # Add a point at the centroid of Bruxelles brux <- bel2_sf[bel2_sf$NAME_1 == "Bruxelles",]

plot(st_geometry(st_centroid(brux)), pch = 20, add = T)

# Add a label for Bruxelles on the map
text(st_coordinates(st_centroid(brux)), labels = "Bruxelles", pos = 3, col = "#9728eb")

## Package mapview

library(mapview)
mapview(bel1)@map