We’ve finally arrived at creating our first maps based on the data we
imported and cleaned in the previous sessions. The focus of this first
session lies on the package tmap
to create maps.
# load libraries
library(tmap)
library(sf)
library(dplyr)
# code based on the original
german_districts <-
sf::read_sf("./data/VG250_KRS.shp") %>%
dplyr::mutate(district_id = as.numeric(AGS))
attributes_districts <- readr::read_delim("./data/attributes_districts.csv", delim = ";")
## Rows: 400 Columns: 7
## ── Column specification ────────────────────────────────────────────────────
## Delimiter: ";"
## dbl (7): district_id, car_density, ecar_share, publictransport_meandist,...
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
german_districts_enhanced <-
german_districts %>%
dplyr::left_join(attributes_districts, by = "district_id") %>%
sf::st_transform(crs = 3035)
# start by setting the tmap mode to "plot" for static maps
tmap_mode("plot") # interactive maps can be designed by changing the mode to "view"
## tmap mode set to plotting
# first maps based on geometrc features
tm_shape(german_districts_enhanced) + # call the shapefile first
tm_fill(col = "lightgrey") # fills the polygons without drawing borders
# ... or use tm_polygons
tm_shape(german_districts_enhanced) +
tm_polygons(col = "lightblue") # fills the polygons and draws borders
In the second step, we want to visualize some information on the German districts contained in the attribute table. Choose a column of interest and create a map. Alternate the map by:
ger_map
.
Combine the following options with a plus sign:
tm_fill(col = "", title = "", palette = "") +
tm_layout(title = "", title.color = "") +
tm_legend(legend.outside = TRUE/FALSE, legend.outside.position = "")
style = ("cat", "fixed", "sd", "equal", "pretty", "quantile", "kmeans", "hclust", "bclust", "fisher", "jenks", "dpih", "headtails", log10_pretty", "cont")
colors()
, R returns the names of all built-in
colors.
<-
.
ger_map <-
tm_shape(german_districts_enhanced) +
tm_fill(col = "publictransport_meandist", # "col" can be the name of a color or a column name
title = "Mean Distances to Stops", # add a title to the legend
palette = "RdPu", # add palette
style = "cont") + # change style
tm_layout(title = "Access Public Transport", # alternate the overall layout like title
title.color = "blue" ) + # changes the font color of the title +
tm_legend(legend.outside = TRUE, # positions the legend outside
legend.outside.position = "left") # defines legend positions
ger_map