# Load libraries
library(readr)
library(dplyr)
library(sf)
library(ggplot2)
library(ggtext)
library(patchwork)
library(showtext)
library(tibble)
# Load geonames for Germany
temp <- tempfile(fileext = ".zip")
download.file(
url = "https://download.geonames.org/export/dump/DE.zip",
destfile = temp,
mode = "wb")
# Name columns in data set
cols <- c(
"geonameid", "name", "asciiname", "alternatenames", "latitude", "longitude",
"feature_class", "feature_code", "country_code", "cc2", "admin1_code",
"admin2_code", "admin3_code", "admin4_code", "population", "elevation", "dem",
"timezone", "modification_date"
)
# Import data set and transform to spatial features
DE <- read_tsv(
unz(temp, "DE.txt"),
col_names = cols,
quote = "",
na = "",
col_types = cols(
.default = col_character(),
geonameid = col_integer(),
latitude = col_double(),
longitude = col_double(),
population = col_double(),
elevation = col_integer(),
dem = col_integer(),
modification_date = col_date()
)
) |>
filter(feature_class == "P") |> # Only populated areas
st_as_sf(coords = c("longitude", "latitude"), crs = st_crs(4326)) |>
st_transform(crs = st_crs(3035)) # Transform to EPSG:3035 (LAEA Europe))
# Create a grid of 10 by 10 km
bbox <- st_bbox(DE)
tile_size = 25000
DE_grid = st_bbox(
c(
xmin = floor(bbox[["xmin"]] / tile_size),
ymin = floor(bbox[["ymin"]] / tile_size),
xmax = ceiling(bbox[["xmax"]] / tile_size),
ymax = ceiling(bbox[["ymax"]] / tile_size)
) * tile_size,
crs = st_crs(3035)
) |>
st_as_sfc() |>
st_make_grid(
cellsize = tile_size,
what = "polygons",
square = TRUE
) |>
st_sf(geometry = _)
DE_grid$cell_id <- seq_len(nrow(DE_grid))
# Count geonames per grid cell
DE_density <- DE_grid |>
mutate(n_geonames = lengths(st_intersects(DE_grid, DE))) |>
filter(n_geonames > 0) |>
mutate(
face = cut(
n_geonames,
breaks = seq(0, max(n_geonames), length.out = 7),
labels = 1:6
) |> as.integer()
)
# Pip positions on a 3 x 3 grid (-1, 0, 1), face written explicitly on every row
pip_layout <- tribble(
~face, ~dx, ~dy,
1, 0, 0,
2, -1, 1,
2, 1, -1,
3, -1, 1,
3, 0, 0,
3, 1, -1,
4, -1, -1,
4, -1, 1,
4, 1, -1,
4, 1, 1,
5, -1, -1,
5, -1, 1,
5, 0, 0,
5, 1, -1,
5, 1, 1,
6, -1, -1,
6, -1, 0,
6, -1, 1,
6, 1, -1,
6, 1, 0,
6, 1, 1
)
spacing <- 0.25 * tile_size # distance of the pips from the cell centre (map units)
cent <- st_centroid(st_geometry(DE_density)) |> st_coordinates()
pips <- DE_density |>
st_drop_geometry() |>
mutate(cx = cent[, "X"], cy = cent[, "Y"]) |>
inner_join(pip_layout, by = "face", relationship = "many-to-many") |>
mutate(
px = cx + dx * spacing,
py = cy + dy * spacing
) |>
st_as_sf(coords = c("px", "py"), crs = st_crs(DE_density))
# The plot ---------------------------------------------------------------------
# Selecting colors
bg_col <- "#1f1b2e"
title_col <- "#f2c14e"
text_col <- "#c0bbd3"
# Selecting fonts
font_add_google("Oswald", "title_font")
font_add_google("Lato", "body_font")
showtext_auto()
showtext_opts(dpi = 300)
# Map only
the_map <- ggplot() +
geom_sf(
data = DE_density,
fill = NA,
colour = text_col, # edge colour; use bg_col for a gap look instead
linewidth = 0.1 # edge width, controlled manually
) +
geom_sf(
data = pips,
colour = text_col,
size = 1.5, # pip size, controlled manually
shape = 16
) +
coord_sf(crs = 3035, datum = NA, expand = FALSE, clip = "off") +
theme_void(base_size = 12)
# helper: one text block, anchored at the top-left of its own panel
text_block <- function(label, family, size_pt, colour) {
ggplot(tibble(x = 0, y = 1, label = label)) +
geom_textbox(
aes(x = x, y = y, label = label),
hjust = 0, vjust = 1,
width = unit(1, "npc"),
box.colour = NA, fill = NA,
box.padding = unit(rep(0, 4), "pt"),
box.margin = unit(rep(0, 4), "pt"),
colour = colour, family = family,
size = size_pt / .pt, # geom_textbox size is in mm, so convert from pt
lineheight = 1
) +
coord_cartesian(
xlim = c(0, 1),
ylim = c(0, 1),
expand = FALSE,
clip = "off") +
theme_void()
}
the_title <- text_block(
"**GeoNames in Germany**",
"title_font", 50, title_col
)
the_subtitle <- text_block(
sprintf(
paste(
"Density of entries for GeoNames in Germany considering only populated",
"places (feature_class \"P\").<br><br>",
"Counts were aggregated to a grid of %d × %d km cells",
"represented here as dice faces.<br><br>",
"Values range between %d and %d entries per dice."
),
tile_size / 1000, tile_size / 1000, min(DE_density$n_geonames),
max(DE_density$n_geonames)
),
"body_font", 18, text_col
)
the_caption <- text_block(
"**Projection:** ETRS89-LAEA (EPSG:3035)<br>**Data Source**: GeoNames",
"body_font", 16, text_col
)
# stack: fixed heights in inches, the spacer absorbs the remaining space
the_side <- the_title / the_subtitle / the_caption / plot_spacer() +
plot_layout(heights = unit(c(2.0, 4.5, 0.5, 1), c("in", "in", "in", "null")))
fig_h <- 8
margin_in <- 0.3
side_w <- 5 # text column width in inches
bb <- st_bbox(DE_density)
asp <- unname((bb["xmax"] - bb["xmin"]) / (bb["ymax"] - bb["ymin"]))
map_w <- asp * (fig_h - 2 * margin_in)
gap_w <- 0.2 # separation between text and map, in inches
fig_w <- side_w + gap_w + map_w + 2 * margin_in
finalPlot <- (the_side | plot_spacer() | the_map) +
plot_layout(widths = c(side_w, gap_w, map_w)) +
plot_annotation(theme = theme(plot.margin = margin(margin_in, margin_in, margin_in, margin_in, "in"))) &
theme(
plot.background = element_rect(fill = bg_col, colour = NA),
panel.background = element_rect(fill = bg_col, colour = NA)
)
ggsave("29-raster.png", finalPlot,
width = fig_w, height = fig_h, dpi = 300, bg = bg_col)