I'm trying to create a map, where I color by German zip codes and I would like to add German states as boundaries.
# for loading our data
library(raster)
library(readr)
library(readxl)
library(sf)
library(dplyr)
# for datasets
library(maps)
library(spData)
# for plotting
library(grid)
library(tmap)
library(viridis)
Get shape files for Germany (link). In Germany zip codes are called Postleitzahlen (PLZ).
germany <- read_sf("data/OSM_PLZ.shp")
Classify PLZs into arbitrary groups for plotting.
germany <- germany %>%
mutate(plz_groups = case_when(
substr(plz, 1, 1) == "1" ~ "Group A",
substr(plz, 2, 2) == "2" ~ "Group B",
TRUE ~ "Group X" # rest
))
Make plot filling by PLZ:
tm_shape(germany) +
tm_fill(col = "plz_groups")
Try to plot the boundaries of the German states ("Bundesland") on top:
tm_shape(germany) +
tm_fill(col = "plz_groups") +
tm_borders(col = "bundesland")
Error in col2rgb(col, alpha = TRUE) : ungültiger Farbname in 'bundesland'
To draw the boundaries of the German states on top you first have to get a shape file for the German states, e.g. from ESRI. Afterwards you could add that shape file via tm_shape
and draw the boundaries via tm_borders
where the col
argument is used to set the color for the border lines. From the docs:
For tm_borders, it is a single color value that specifies the border line color.
library(sf)
library(dplyr)
library(tmap)
germany <- read_sf("Postleitzahlengebiete_-_OSM/OSM_PLZ.shp")
german_states <- read_sf("Bundesl%C3%A4ndergrenzen_2018/Bundesländergrenzen_2018.shp")
germany <- germany %>%
mutate(plz_groups = case_when(
substr(plz, 1, 1) == "1" ~ "Group A",
substr(plz, 2, 2) == "2" ~ "Group B",
TRUE ~ "Group X" # rest
))
tm_shape(germany) +
tm_fill(col = "plz_groups") +
tm_shape(german_states) +
tm_borders(col = "black")