Reputation: 183
I'm working with package ggplot2
and using the function geom_map
to fill
the countries with different colors.
I was wondering if it is possible to fill with flags instead of colors?
Desired result:
I'm doing:
ALL_EU <-c("Russia", "Germany", "UK", "France", "Italy", "Spain", "Ukraine", "Poland", "Romania", "Netherlands", "Belgium", "Czech Republic", "Greece", "Portugal", "Sweden", "Hungary", "Belarus", "Austria", "Serbia", "Switzerland", "Bulgaria", "Denmark", "Finland","Slovakia", "Norway", "Ireland", "Croatia", "Moldova", "Bosnia and Herzegovina","Albania", "Lithuania", "North Macedonia", "Slovenia", "Latvia", "Estonia","Montenegro", "Luxembourg" , "Malta", "Iceland", "Andorra", "Monaco", "Liechtenstein","San Marino", "Vatican", "Kosovo")
#Filter some regions out just for plot
world_map <- map_data("world",region = ALL_EU[-which(ALL_EU%in%c("Russia","Iceland"))])
world_map <- world_map%>%filter(subregion!="Svalbard"&subregion!="Jan Mayen"|is.na(subregion))
and then plot it, note that in this case I use fill = "Flags"
so I can then change the color and legend with scale_fill_manual
, also I make all countries blue just for a reproducible example.
ggplot() +
theme_void()+
geom_map(dat = world_map,map = world_map,
aes(map_id = region,fill = "Flags"),color = "gray",size = 0.25)+
scale_fill_manual(name = "Countries", values = c("Flags" = "blue"))+
expand_limits(x = world_map$long, y = world_map$lat)
Also, and even if its possible, fill several countries with, for example, the flag of the European Union. But this is probably for another question. Thank you!
Upvotes: 2
Views: 549
Reputation: 50738
Here is an option using the excellent ggpattern
and flagon
packages.
# Get mapping of country codes to countries; need this to select the right
# flags by country codes as provided by `flagon`
# Must also clean up country names to match those from `world_map`
library(tidyverse)
library(flagon)
data_flags <- flagon::country_codes %>%
select(country, ccode) %>%
mutate(flag = flagon::flags(ccode)) %>%
mutate(country = case_when(
str_detect(country, "Macedonia") ~ "North Macedonia",
str_detect(country, "Moldova") ~ "Moldova",
str_detect(country, "Vatican") ~ "Vatican",
str_detect(country, "United Kingdom") ~ "UK",
TRUE ~ country)) %>%
filter(country %in% ALL_EU)
library(ggpattern)
world_map %>%
left_join(data_flags, by = c("region" = "country")) %>%
filter(!is.na(flag)) %>%
ggplot() +
theme_void() +
geom_map_pattern(
map = world_map,
aes(map_id = region, pattern_type = region, pattern_filename = I(flag)),
pattern = "image",
pattern_type = "expand",
color = "gray",
size = 0.25) +
expand_limits(x = world_map$long, y = world_map$lat)
Upvotes: 2