Invisible link to canonical for Microformats

Beautiful maps with R (IV): Fun with flags revisited

Any picture as a basemap


On 27 Jan. 2022 my package rasterpic was accepted on CRAN (Hooray!). This package geotags images, using a spatial object (from sf or terra) as a geographic reference.

I tweeted about that, and it seems to have received good feedback from the #rspatial community:

I also received an interesting reply to this from Hefin Ioan Rhys @HRJ21:

That reminds me of a previous post that I wrote when I added some new functions to the cartography package, now replaced by the mapsf package.

With rasterpic, we now have an alternative tool for creating maps using images, and this quick post shows you how to do it.

I will replicate the Africa map presented in my previous plot, but this time I will use newer packages, such as giscoR, and the development version of ggspatial (not released yet), which adds support for SpatRaster objects in ggplot2. The flags will be extracted from the GitHub repository https://github.com/hampusborgos/country-flags.


# Development version of ggspatial
# devtools::install_github("paleolimbot/ggspatial")
library(ggspatial)
library(ggplot2)
library(giscoR)
library(dplyr)
library(rasterpic)

# For country names
library(countrycode)

world <- gisco_get_countries(epsg = 3857)
africa <- gisco_get_countries(region = "Africa", epsg = 3857)

# Base map of Africa
plot <- ggplot(world) +
  geom_sf(fill = "grey90") +
  theme_minimal() +
  theme(panel.background = element_rect(fill = "lightblue"))

plot +
  # Zoom on Africa
  coord_sf(
    xlim = c(-2000000, 6000000),
    ylim = c(-4000000, 5000000)
  )

plot of chunk 20220128_africa

Now, let’s add the flags with a loop:


# We paste the ISO2 code to each African country
africa$iso2 <- countrycode(africa$ISO3_CODE, "iso3c", "iso2c")

# Get flags from repo - low quality to speed up the code
flagrepo <- "https://raw.githubusercontent.com/hjnilsson/country-flags/master/png250px/"

# Loop and add
for (iso in africa$iso2) {
  # Download pic and plot
  imgurl <- paste0(flagrepo, tolower(iso), ".png")
  tmpfile <- tempfile(fileext = ".png")
  download.file(imgurl, tmpfile, quiet = TRUE, mode = "wb")

  # Raster
  x <- africa %>% filter(iso2 == iso)
  x_rast <- rasterpic_img(x, tmpfile, crop = TRUE, mask = TRUE)
  plot <- plot + layer_spatial(x_rast)
}

plot +
  geom_sf(data = africa, fill = NA) +
  # Zoom on Africa
  coord_sf(
    xlim = c(-2000000, 6000000),
    ylim = c(-4000000, 5000000)
  )

plot of chunk 20220128_flag


Related posts