knitr::opts_chunk$set(echo = T, warning = FALSE,message = F)
if (!require("rworldmap")) {
  install.packages("rworldmap")
  library(rworldmap)
}
# ggplot2, ggFlags, dplyr are needed for the bar charts
library(ggplot2)
library(dplyr)
if (!require("ggflags")) {
  devtools::install_github("rensa/ggflags")
  library(ggflags)
}

library(countrycode)

# csv file with each person as a row and containing a column with the header Origin and
# countries in 2-letter ISO format (change joinCode for other formats)

df1 <- readxl::read_excel("AVRR_MASTER.xlsx",sheet = "AVRR")

names(df1)[9] <- "CoO"
names(df1)[10] <- "Total"


df1 <- df1 %>%
group_by(CoO,Total)
df1$CoO <- countrycode(sourcevar = df1$CoO, "country.name","iso2c")

countries_lab <- as.data.frame(table(df1$CoO))

colnames(countries_lab) <- c("country", "value")


matched <- joinCountryData2Map(countries_lab, joinCode="ISO2", nameJoinColumn="country")
## 40 codes from your data successfully matched countries in the map
## 0 codes from your data failed to match with a country code in the map
## 203 codes from the map weren't represented in your data
countries_lab %>%
  mutate(code = tolower(country),
         countries = countrycode(sourcevar = countries_lab$country, "iso2c","country.name")) %>%
  filter(value > 50)%>%
  ggplot(aes(x = reorder(countries, value), y = value)) +
  geom_bar(stat = "identity") +
  geom_flag(y = -1, aes(country = code), size = 10) +
  scale_y_continuous(expand = c(0.1, 1)) +
  xlab("Country") +
  ylab("Members") +
  theme_bw() +
  theme(legend.title = element_blank(),
        axis.text.y = element_text(size = 12),
        axis.title.y = element_blank(),
        axis.title.x = element_blank()) +
  geom_text(aes(label = value),hjust = -0.2)+
  coord_flip()+
  labs(
    title = "Lorem Ipsum"
  )

mapCountryData(matched,
               nameColumnToPlot="value",
               mapTitle= "Lorem Ipsum",
               catMethod = "logFixedWidth",
               colourPalette = "heat",
               oceanCol="lightblue",
               missingCountryCol="white",
               addLegend = FALSE,
               lwd = 1)

dev.off()
## null device 
##           1