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). Examples were tested on Macrobond version 1.25, Macrobond API for R version 1.2-8 and R 4.2.0.

See method of constructing choropleth map - with ggplot2, rgdal and broom - 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, rgdal and broom packages (click to enlarge). 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 + rgdal and broom packages

library(MacrobondAPI)
library(tidyverse)
library(countrycode)
library(rgdal)
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
ISO<-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){
  ISO<-append(ISO, getMetadataValues(getMetadata(FetchOneTimeSeries(i)), "Region"))
}

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

#prepare data frame
data <- data.frame(values, ISO, country) %>%
  drop_na() %>%
  mutate(ISO=str_to_upper(ISO)) #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 rgdal library. You'll get a Spdf object (spatial polygon data frame).
my_spdf <- readOGR( 
  dsn= paste0("C:/Users/malgorzata.matachows/Desktop/R/DATA/") , 
  layer="TM_WORLD_BORDERS_SIMPL-0.3",
  verbose=FALSE)

#You can build a map with ggplot2, but it works with data frames, not geospatial data. You need to use broom library to clean it.
#cleaning
spdf_cleaner <- tidy(my_spdf) 
#Unfortunately the information about regions is lost, you need to create additional data frame.
#create data frame with ISO data
temp_df <- data.frame(my_spdf@data$ISO2)
names(temp_df) <- c("ISO")
#create and append "id"
temp_df$id <- as.character(seq(0,nrow(temp_df)-1)) #assign class so you can join by that column
#create data frame
spdf_cleaner <- inner_join(spdf_cleaner, temp_df, by="id")


###DATA + MAP
#join map info and data
spdf_final <-  full_join(spdf_cleaner , data, by="ISO")

#plot
ggplot() +
  geom_polygon(data = spdf_final, aes(fill = values, x = long, y = lat, group = group)) +
  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), 
                     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))