Most likely, no one ever got rich by making pink web maps, but it does add a certain joy to your day, so let’s do it. We are going to need a few data sets:
- Polygons – I´ve had my eyes on the R giscoR package for a while, so I used that to fetch polygons for the German regions.
- Data to visualize – To start with something simple, I used population data from www.destatis.de/
# Load libraries
library(dplyr)
library(giscoR)
library(htmlwidgets)
library(leaflet)
library(readxl)
library(sf)
library(stringr)
# Set working directory
setwd("C:\\Eget\\R\\")
# Get administrative boundaries for regions in Germany, NUTS level 1
germany <- gisco_get_nuts(country = "Germany",
nuts_level = 1,
resolution = "3")
germany$NUTS_NAME = str_to_title(germany$NUTS_NAME, locale = "en") # Convert name to title case
# Read Excel file with population data
# Data from https://www.destatis.de/EN/Themes/Society-Environment/Population/Current-Population/Tables/population-by-laender.html
population <- read_excel("Indata\\Germany population.xlsx",sheet = "Population")
# Join GeoPackage and Excel file
germany = left_join(germany, population, by = join_by("NUTS_NAME" == Name))
# Create palette
bins <- c(0, 1000000, 5000000, 10000000, 15000000, 20000000)
pal <- colorBin("RdPu", domain = germany$Population, bins = bins)
# Create palette
bins <- c(500000, 1000000, 5000000, 10000000, 15000000, 20000000)
pal <- colorBin("RdPu", domain = germany$Population, bins = bins)
# Create Leaflet web map
Germany_webmap = leaflet(germany) %>%
setView(lng = 10, lat = 51, zoom = 5) %>%
addProviderTiles(
providers$CartoDB.Positron,
group = "Positron") %>%
addPolygons(
fillColor = ~pal(Population),
weight = 2,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7,
highlightOptions = highlightOptions(
weight = 5,
color = "#666",
dashArray = "",
fillOpacity = 0.7,
bringToFront = TRUE),
popup = ~as.character(Population),
label = ~as.character(NUTS_NAME),
) %>%
addLegend(
pal = pal,
values = ~population,
opacity = 0.7,
title = "Population 2022",
position = "bottomright")
# Save map to disk
saveWidget(widget = Germany_webmap, file = "Germany_webmap.html")
The result:
Inspired by https://rstudio.github.io/leaflet/ and https://ropengov.github.io/giscoR/.
For more web mapping examples: