In order to access trade information, we’ll use the comtradr package which provides an API access to the UN Comtrade Database.
library(comtradr)
Suppose we want to analyze the Algerian exports’ evolution (Montary values of goods and services) in relation to the Ouest-European market which represents an important one. To that aim, we’ll use the ct_search function.
export_DZ <- ct_search(reporters = "Algeria",
partners = c("France", "Spain", "Italy", "Germany"),
trade_direction = "exports")
#Note that the API limitS our request to 5 partner. For more information on API limits, refer to the the comtradr documentation.
Let us embellish our database and select the relevant information
library(tidyverse)
export_DZ <- as_tibble(export_DZ)
export_DZ <- export_DZ %>% select(year, partner, trade_value_usd)
head(export_DZ)
## # A tibble: 6 x 3
## year partner trade_value_usd
## <int> <chr> <dbl>
## 1 2017 France 4431261656
## 2 2017 Germany 14045034
## 3 2017 Italy 5629479666
## 4 2017 Spain 4103370763
## 5 2012 France 6124176488
## 6 2012 Germany 238172929
Finally, let’s plot our data to have a broader overview
options(scipen = 999) # avoiding scientific values (e.g. 10e9)
ggplot(export_DZ, aes(x = year, y= ((trade_value_usd)/1000))) +
facet_grid( ~ as.factor(partner))+
geom_line(size = 2, color = "lightgreen") +
ylab("trade value in 1000$")+
xlab("years")+
scale_x_continuous(breaks = c(seq(1992, 2015, by = 2), 2017))+
theme(axis.text.x = element_text(angle = 90, hjust = 1))
Interesting to see that the export value towards Germany is relatively low. Let us compare the exports to the imports.
import_DZ <- ct_search(reporters = "Algeria",
partners = c("France", "Spain", "Italy", "Germany"),
trade_direction = "imports")
We’ll use the patchwork package to combine the import and the export plots. It’s as easy as drinking from a bottle of water.
library(patchwork)
max <- max(import_DZ$trade_value_usd/1000, export_DZ$trade_value_usd/1000)
min <- min(import_DZ$trade_value_usd/1000, export_DZ$trade_value_usd/1000)
p1 <- ggplot(export_DZ, aes(x = year, y= ((trade_value_usd)/1000))) +
facet_grid( ~ as.factor(partner))+
geom_line(color = "#FF5E00") +
ylab("exports value in 1000$")+
xlab("years")+
scale_x_continuous(breaks = c(seq(1992, 2015, by = 4), 2017))+
theme(axis.text.x = element_text(angle = 90, hjust = 1))
p2 <- ggplot(import_DZ, aes(x = year, y= ((trade_value_usd)/1000))) +
facet_grid( ~ as.factor(partner))+
geom_line(color = "#FF00A2") +
ylab("imports value in 1000$")+
xlab("years")+
scale_x_continuous(breaks = c(seq(1992, 2015, by = 4), 2017))+
theme(axis.text.x = element_text(angle = 90, hjust = 1))
p1 + p2 + patchwork::plot_layout(ncol = 1) + ylim(min, max)
# ylim(min, max) allows us to have the same dimensiality in our two plots.