Choropleth map (incl. automated search)

Macrobond R API is available for users with Data+ and Legacy license (the latter without searching and revision history functions). Example was tested on Macrobond version 1.27, Macrobond API for R version 1.2-8 and R 4.2.0.

See method of constructing choropleth map - with ggplot2 and sf - based on a shape file. Example is presented on World Development Indicator - Population Ages 65 & Above data from World Bank. Jump to the code.

Map created with ggplot2 and sf packages. Search query is based on concept metadata. You only need code for one series and the rest is downloaded automatically. To see not-based-on-search method see Circular bar chart method.

Based on a shape file, with 'search by concept', ggplot2 + sf packages

library(MacrobondAPI)
library(tidyverse)
library(countrycode)
library(sf) #for map's shape
library(broom)
library(viridis) #for colors

###DATA PART
#choose series
series<-FetchOneTimeSeries("af_sp_pop_65up_to_zs")
#get the concept of a series and create search query based on it
query <- CreateSearchQuery() 
setEntityTypeFilter(query, "TimeSeries") 
addAttributeValueFilter(query, "RegionKey", getConcepts(series)) 
country_set <- getEntities(SearchEntities(query))

#create empty vectors
list_of_series<-NULL
values<-NULL
ISO2<-NULL
country<-NULL

#get list of series' codes
for (i in country_set){
  list_of_series<-append(list_of_series, getName(i))
}

#get last values 
for (i in list_of_series){
  values<-append(values, last(getValues(FetchOneTimeSeries(i))))
}

#get countries ISO codes
for (i in list_of_series){
  ISO2<-append(ISO2, getMetadataValues(getMetadata(FetchOneTimeSeries(i)), "Region"))
}

#change ISO codes to country names
country<-countrycode(as.vector(ISO2), origin="iso2c", destination ="country.name")

#prepare data frame
data <- data.frame(values, ISO2, country) %>%
  drop_na() %>%
  mutate(ISO2=str_to_upper(ISO2)) #shape file has ISO codes in upper cases


###MAP INFO PART (based on a shape file)
#This example uses shape file from: http://thematicmapping.org/downloads/TM_WORLD_BORDERS_SIMPL-0.3.zip

#Read shape file with the sf library. You'll get a data frame.
map <- st_read("C:/Users/name.name/Desktop/R/DATA", 
layer="TM_WORLD_BORDERS_SIMPL-0.3")

###DATA + MAP
#join map info and data
map_final <- full_join(map , data, by="ISO2")

#plot
ggplot() +
  geom_sf(data = map_final, colour = "black", size = 0.2, aes(fill = values)) +
  theme_void()+
  ggtitle("Percentage of population ages 65 and above")+
  scale_fill_viridis(option="D", direction=-1, #color scale's & legend's settings
                     breaks=c(5,10,15,20,25,30,35), 
                     name=" %")+
  theme(plot.title=element_text(size=rel(1.5), hjust=0.5), #additional settings for title and legend
        legend.position=c(0.15, 0.35))