Choropleth map with R

Cedric Vidonne

Lei Chen

Choropleth map with R

A choropleth map is a type of thematic map in which areas are shaded or patterned according to a data variable. The variable is categorized into intervals, with each interval represented by a colour, and the map filled accordingly.

More about: Choropleth map


Choropleth map

# Loading required packages
library(unhcrthemes)
library(tidyverse)
library(scales)
library(sf)

# Load data
df <- read_csv("https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/geospatial/choropleth_map.csv")
poly_url <- "https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/geospatial/world_polygons_simplified.json"
line_url <- "https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/geospatial/world_lines_simplified.json"

# Add CRS to poly and join values from csv
poly <- read_sf(poly_url) |> 
  st_set_crs(4326) |> 
  left_join(df, by = c("color_code" = "iso3")) |> 
  mutate(legend = case_when(
    refugees < 1e4 ~ "<10k",
    refugees < 1e5 ~ "10k-100k",
    refugees < 1e6 ~ "100k-1M",
    is.na(refugees) ~ NA_character_,
    TRUE ~ ">1M"
  )) |> 
  mutate(legend = as_factor(legend) |> 
           fct_relevel("<10k", "10k-100k", "100k-1M", ">1M"))
  

# Sort line type
line <- read_sf(line_url) |>
  mutate(
    type = as_factor(type) |>
      fct_relevel("solid", "dashed", "dotted", "dashed-dot")
  ) |> 
  st_set_crs(4326)


# Plot
ggplot() +
  geom_sf(data = poly,
          aes(fill = legend),
          color = "transparent") +
  geom_sf(data = line,
          aes(linetype = type),
          color = "white",
          linewidth = .25,
          show.legend = FALSE) +
  coord_sf(crs = st_crs('ESRI:54030'),
           expand = FALSE) +
  scale_linetype_manual(values = c(1, 2, 3, 4)) +
  scale_fill_unhcr_d(palette = "pal_blue") +
  labs(
    title = "Global refugee displacement by country of asylum | 2021",
    caption = "The boundaries and names shown and the designations used on this map do not imply official\nendorsement or acceptance by the United Nations.\nSource: UNHCR Refugee Data Finder\n© UNHCR, The UN Refugee Agency"
  ) +
  theme_unhcr_map(rel_small = .75,
                  rel_tiny = .65)


Related chart with R