Commented Scripts to Build Maps with cartography

Timothée Giraud, Nicolas Lambert

2017-11-13

How to Import a Geospatial Vector Data File

The rgdal Way

library(rgdal)
## Loading required package: sp
## rgdal: version: 1.2-15, (SVN revision 691)
##  Geospatial Data Abstraction Library extensions to R successfully loaded
##  Loaded GDAL runtime: GDAL 2.1.2, released 2016/10/24
##  Path to GDAL shared files: /usr/local/share/gdal
##  GDAL binary built with GEOS: TRUE 
##  Loaded PROJ.4 runtime: Rel. 4.9.2, 08 September 2015, [PJ_VERSION: 492]
##  Path to PROJ.4 shared files: (autodetected)
##  Linking to sp version: 1.2-5
# path to the ESRI Shapefile embedded in cartography
path_to_file <- system.file("shape/martinique.shp", package="cartography")
mtq <- readOGR(dsn = path_to_file, verbose = FALSE)
class(mtq)
## [1] "SpatialPolygonsDataFrame"
## attr(,"package")
## [1] "sp"
plot(mtq)

The sf Way

library(sf)
## Linking to GEOS 3.5.1, GDAL 2.1.2, proj.4 4.9.2, lwgeom 2.3.3 r15473
# path to the ESRI Shapefile embedded in cartography
path_to_file <- system.file("shape/martinique.shp", package="cartography")
mtq <- st_read(dsn = path_to_file, quiet = TRUE)
class(mtq)
## [1] "sf"         "data.frame"
plot(st_geometry(mtq))

Europe Dataset

library(cartography)
# Load data
data(nuts2006)

# Plot a layer with the extent of the EU28 countries with only a background color
plot(nuts0.spdf, border = NA, col = NA, bg = "#A6CAE0")
# Plot non european space
plot(world.spdf, col  = "#E3DEBF", border=NA, add=TRUE)
# Plot a layer of countries borders
plot(nuts0.spdf, border = "grey20", lwd = 3, add = TRUE)
# Plot a layer of NUTS1
plot(nuts1.spdf, border = "grey30", lwd = 2, add = TRUE)
# Plot a layer of NUTS2
plot(nuts2.spdf, border = "grey40", lwd = 0.5, add = TRUE)
# Plot a layer of NUTS3
plot(nuts3.spdf, border = "grey20", lwd = 0.1, add = TRUE)

Label Map

# Layout plot
layoutLayer(title = "Most Populated Countries of Europe", # title of the map
            author = "",  # no author text
            sources = "", # no source text
            scale = NULL, # no scale
            col = NA, # no color for the title box 
            coltitle = "black", # color of the title
            frame = FALSE,  # no frame around the map
            bg = "#A6CAE0", # background of the map
            extent = nuts0.spdf) # set the extent of the map

# Non European space
plot(world.spdf, col = "#E3DEBF", border = NA, add = TRUE)
# European (EU28) countries
plot(nuts0.spdf, col = "#D1914D",border = "white", lwd = 1, add = TRUE)

# Selection of the 10 most populated countries of Europe
dflab <- nuts0.df[order(nuts0.df$pop2008, decreasing = TRUE),][1:10,]
# Label creation
dflab$lab <- paste(dflab$id, "\n", round(dflab$pop2008/1000000,0), "M", sep ="")

# Label plot of the 10 most populated countries
labelLayer(spdf = nuts0.spdf, # SpatialPolygonsDataFrame used to plot he labels
           df = dflab, # data frame containing the lables
           txt = "lab", # label field in df
           col = "#690409", # color of the labels
           cex = 0.9, # size of the labels
           font = 2) # label font

# Add an explanation text
text(x = 5477360, y = 4177311, labels = "The 10 most populated countries of Europe
Total population 2008, in millions of inhabitants.", cex = 0.7, adj = 0)

Choropleth Map

# Compute the compound annual growth rate
nuts2.df$cagr <- (((nuts2.df$pop2008 / nuts2.df$pop1999)^(1/9)) - 1) * 100

# Set a custom color palette
cols <- carto.pal(pal1 = "green.pal", # first color gradient
                  n1 = 2, # number of colors in the first gradiant
                  pal2 = "red.pal", # second color gradient
                  n2 = 4) # number of colors in the second gradiant

# Plot a layer with the extent of the EU28 countries with only a background color
plot(nuts0.spdf, border = NA, col = NA, bg = "#A6CAE0")
# Plot non european space
plot(world.spdf, col  = "#E3DEBF", border=NA, add=TRUE)

# Plot the compound annual growth rate
choroLayer(spdf = nuts2.spdf, # SpatialPolygonsDataFrame of the regions
           df = nuts2.df, # data frame with compound annual growth rate
           var = "cagr", # compound annual growth rate field in df
           breaks = c(-2.43,-1,0,0.5,1,2,3.1), # list of breaks
           col = cols, # colors 
           border = "grey40", # color of the polygons borders
           lwd = 0.5, # width of the borders
           legend.pos = "right", # position of the legend
           legend.title.txt = "Compound Annual\nGrowth Rate", # title of the legend
           legend.values.rnd = 2, # number of decimal in the legend values
           add = TRUE) # add the layer to the current plot

# Plot a layer of countries borders
plot(nuts0.spdf,border = "grey20", lwd=0.75, add=TRUE)

# Layout plot
layoutLayer(title = "Demographic Trends", author = "cartography", 
            sources = "Eurostat, 2008", frame = TRUE, col = NA, 
            scale = NULL,coltitle = "black",
            south = TRUE) # add a south arrow

Base Map and Proportional Symbols

## Plot OpenStreetMap tiles as basemap 
# Download the tiles, nuts0.spdf extent
EUosm <- getTiles(spdf = nuts0.spdf, type = "osm", zoom = 4)
## Warning: spdf is deprecated; use x instead.
# Plot the tiles
tilesLayer(EUosm)

# Plot countries
plot(nuts0.spdf, border = "grey65", lwd = 2, add=TRUE)

# Plot countries population 
nuts0.df$pop <- nuts0.df$pop2008 / 1000
propSymbolsLayer(spdf = nuts0.spdf, # SpatialPolygonsDataFrame of the countries
                 df = nuts0.df,  # data frame of the regions
                 var = "pop",  # population
                 symbols = "circle", # type of symbol
                 border = "white", # color of the symbols borders
                 lwd = 1.5, # width of the symbols borders
                 legend.pos = "topleft",
                 legend.title.txt = "Total population\n(in thousands)")
# # Layout plot
layoutLayer(title = "Countries Population in Europe",
            sources = "Data: Eurostat, 2008",
            author = "Base map: Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA.",
            scale = NULL, frame = TRUE,
            col = "#688994") # color of the frame

Link/Flow Map

# Create a link layer from the twincities data frame
head(twincities.df)
##      i    j fij
## 1 DE14 AT11   1
## 2 DE21 AT11   1
## 3 DE23 AT11   1
## 4 DE26 AT11   2
## 5 DE91 AT11   1
## 6 DEB3 AT11   1
# twincities contains links between Nuts 2 regions
# ?twincities.df
twincities.spdf <- getLinkLayer(x = nuts2.spdf, # SpatialPolygonsDataFrame of Nuts2
                                df = twincities.df) # links data frame

# Plot a layer with the extent of the EU28 countries with only a background color
plot(nuts0.spdf, border = NA, col = NA, bg = "#A6CAE0")
# Plot non european space
plot(world.spdf, col  = "#E3DEBF", border=NA, add=TRUE)
# Plot Nuts2 regions
plot(nuts2.spdf, col = "#D1914D",border = "grey80", add=TRUE)

# # Plot links with graduated sizes
gradLinkLayer(x = twincities.spdf, # SpatialLinesdataFrame of the links
              df = twincities.df, # data frame of the links
              var = "fij", # name of the variable used to plot the links widths
              breaks = c(2,5,15,20,30), # list of breaks
              lwd = c(0.1,1,4,10), # list of widths
              col = "#92000090", # color of the links
              legend.pos = "right", legend.frame = TRUE,
              legend.title.txt = "Number of Aggreements\n(regional level)",
              add = TRUE)

# Plot the layout
layoutLayer(title = "International Twinning Agreements Between Cities", 
            author = "cartography", sources = "Sources: Adam Ploszaj & Wikipedia, 2011",
            scale = NULL, south = TRUE, frame = TRUE, col = NA, 
            coltitle = "black")