knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 7, fig.height = 5 ) library(dplyr)
ukgeog
provides several read_*
functions to provide the ability to easily download official spatial data sets of the UK as simple feature (sf
) objects. A full list of the geographies available is provided here. Here we demonstrate how this makes it easy to make choropleth maps with base R, as well as with popular packages such as ggplot2
, tmap
and leaflet.
First we need to read in a spatial dataset as a simple feature (sf
), here we choose to make use of read_admin
to read in the countries that make up the UK:
library(ukgeog) sf <- read_sf("NAT", year = 2021)
Note: crs = 4326
(the default) provides the most compatibility with other functions.
We first merge in mid-2019 population density estimates from the ONS, so we have something to plot:
population <- data.frame( country = c("England", "Wales", "Scotland", "Northern Ireland"), `Population Density` = as.numeric(c("432", "152", "70", "137")), check.names = FALSE ) sf <- dplyr::left_join(sf, population, by = "country")
Now we plot some choropleth maps with both base R and some easier to use packages:
plot
)cols <- c("#EDF8E9", "#BAE4B3", "#74C476", "#31A354", "#006D2C") brks <- c(0, 100, 200, 300, 400, 500) col <- cols[findInterval(sf$`Population Density`, vec = brks)] plot(sf$geometry, col = col) legend("bottomleft", legend = levels(cut(sf$`Population Density`, brks)), fill = cols, title = "Population Density")
ggplot2
library(ggplot2) ggplot(sf) + geom_sf(aes(fill = `Population Density`)) + theme_void()
tmap
library(tmap) qtm(sf, fill = "Population Density") + tm_legend(legend.position = c("left", "top"))
leaflet
library(leaflet) leaflet(sf) %>% addPolygons()
# library(leaflet) # library(mapview) # # mapshot(leaflet(sf) %>% addPolygons(), # file = './leaflet.png') # # #{width=400px}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.