knitr::opts_chunk$set(
                      comment = "#>",
                      message=FALSE, 
                      warning=FALSE,
                      #fig.retina = 2, 
                      fig.width = 8,
                      fig.asp = 0.718,
                     # fig.align = "center",
                     # dev = "ragg_png",
                      out.width = "90%"
)
unlink(".RData")
library(testthat)
library(ggplot2)
library(tidyverse)
library(scales)
library(unhcrthemes)
# library(extrafont) 
# font_import()
# loadfonts()
# font_install('fontcm')

dict_pop_type_name <- c(
  'refugees' = 'Refugees',
  'returned_refugees' = 'Returned refugees',
  'asylum_seekers' = 'Asylum-seekers',
  'idps' = 'Internally displaced persons',
  'returned_idps' = 'Returned idps',
  'oip' = 'Other people in need of international protection',
  'stateless' = 'Stateless people',
  'ooc' = 'Others of concern to UNHCR',
  'hst' = 'Host community'
)


dict_pop_type_label <- c(
  'refugees' = 'REF',
  'returned_refugees' = 'RETURNED_REF',
  'asylum_seekers' = 'ASY',
  'idps' = 'IDP',
  'returned_idps' = 'RETURNED_IDP',
  'oip' = 'OIP',
  'stateless' = 'STA',
  'ooc' = 'OOC',
  'hst' = 'HST'
)


cols_poptype_name_name <- c("Asylum-seekers" = "#18375F",
                  "Refugees" = "#0072BC",
                  "Other people in need of international protection" = "#EF4A60", 
                  "Others of concern to UNHCR" = "#999999",
                  "Internally displaced persons" = "#00B398",
                  "Stateless people" = "#E1CC0D")


cols_poptype_label <- c("ASY" = "#18375F",
                  "REF" = "#0072BC",
                  "OIP" = "#EF4A60", 
                  "OOC" = "#999999",
                  "IDP" = "#00B398",
                  "STA" = "#E1CC0D")                  
# Load already included functions if relevant
pkgload::load_all(export_all = FALSE)

Below is the library with all Country Focused questions organised around the 7 key questions!

1. Category

Key Figures

#' Summary Key Figures
#' 
#'  Key figures can be highlighted with humanitarian icons
#'   https://fontawesome.com/icons/categories/humanitarian  
#' @param year Numeric value of the year (for instance 2020)
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' @return ggplot2
#' 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join
#' @importFrom ggtext geom_textbox
#' @importFrom unhcrthemes theme_unhcr countrycode
#' @importFrom tidyr pivot_longer
#' @importFrom extrafont fonttable font_import
#' @importFrom sysfonts font_add
#' @importFrom utils download.file
#' 
#' @export

plot_ctr_keyfig <- function(country_asylum_iso3c, year){

country_name_text <- nansen::countries  |> 
  dplyr::filter(iso_code == country_asylum_iso3c) |>
  dplyr::distinct(name) |>
  dplyr::pull()

total_poc <- nansen::population |> 
  tidyr::pivot_longer(
    cols = refugees:hst,
    names_to = "population_type",
    values_to = "value"
  ) |> 
  dplyr::filter(year == year,
                coa_iso == country_asylum_iso3c) |>
  dplyr::summarise(sum(value, na.rm = TRUE)) |>
  dplyr::pull()

total_poc_last_year <- nansen::population |> 
  tidyr::pivot_longer(
    cols = refugees:hst,
    names_to = "population_type",
    values_to = "value"
  ) |> 
  dplyr::filter(year == as.numeric(year)-1,
                coa_iso == country_asylum_iso3c) |>
  dplyr::summarise(sum(value, na.rm = TRUE)) |>
  dplyr::pull()

perc_change_poc <- ((total_poc - total_poc_last_year)/total_poc_last_year)*100

total_ref  <- nansen::population |> 
  dplyr::filter(year == year,
                coa_iso == country_asylum_iso3c)|>
  dplyr::summarise(sum(refugees, na.rm = TRUE)) |>
  dplyr::pull()


total_asy <- nansen::population |> 
  dplyr::filter(year == year,
                coa_iso == country_asylum_iso3c)|>
  dplyr::summarise(sum(asylum_seekers, na.rm = TRUE)) |>
  dplyr::pull()

total_oip <- nansen::population |> 
  dplyr::filter(year == year,
                coa_iso == country_asylum_iso3c)|>
  dplyr::summarise(sum(oip, na.rm = TRUE)) |>
  dplyr::pull()

total_idp <- nansen::population |> 
  dplyr::filter(year == year,
                coa_iso == country_asylum_iso3c)|>
  dplyr::summarise(sum(idps, na.rm = TRUE)) |>
  dplyr::pull()

total_sta <- nansen::population |> 
  dplyr::filter(year == year,
                coa_iso == country_asylum_iso3c)|>
  dplyr::summarise(sum(stateless, na.rm = TRUE)) |>
  dplyr::pull()

total_ooc <- nansen::population |> 
  dplyr::filter(year == year,
                coa_iso == country_asylum_iso3c)|>
  dplyr::summarise(sum(ooc, na.rm = TRUE)) |>
  dplyr::pull()

## Create the frame to be displayed with a facetted ggplot  
keyfig <- data.frame(
  ## order the factor for correct display
  fig = factor( c("Refugees", "Asylum-seekers", "Other in Need in International Protection",
               "Internally Displaced People", "Stateless People", "Others of Concerns"),
               levels = c("Refugees",
                          "Asylum-seekers",
                          "Other in Need in International Protection",
                          "Internally Displaced People",
                          "Stateless People",
                          "Others of Concerns")),  
  pal = c("REF", "ASY",  "OIP", "IDP",  "STA", "OOC"),
  icon = c("\ue4fb", # "Refugees" fa-hands-holding-circle
           "\ue553", # "Asylum-seekers" fa-person-walking-dashed-line-arrow-right
           "\ue54d", # "Other in Need in International Protection"fa-person-rays
           "\ue552", #  "Internally displaced people" fa-person-walking-arrow-right
           "\ue4b9", # "Stateless People" fa-arrows-down-to-people
           "\ue539" #  "Others of Concerns"  fa-person-arrow-up-from-line
           ),
  label = c(
  paste0(format(round(total_ref, 0), scientific = FALSE, big.mark = ",")),
  paste0(format(round(total_asy, 0), scientific = FALSE, big.mark = ",")),
  paste0(format(round(total_oip, 0), scientific = FALSE, big.mark = ",")),
  paste0(format(round(total_idp, 0), scientific = FALSE, big.mark = ",")),
  paste0(format(round(total_sta, 0), scientific = FALSE, big.mark = ",")),
  paste0(format(round(total_ooc, 0), scientific = FALSE, big.mark = ",")))
  )


 p <- ggplot(keyfig) +  
  ggtext::geom_textbox(aes(x = 0.3, 
                           y = 1,  
                 label = icon ,
                 color =  pal), 
                family = "Font Awesome 6 Free Solid",
                box.colour = NA , 
                hjust = 0, 
                vjust = 0,
               size = 13) +
  ggtext::geom_textbox(aes(x =  0.3, 
                           y =  1, 
                           label = label ,
                           color =  pal), 
                       family = "Lato", 
                       hjust = -0.5, 
                       vjust = 0,
                       size = 12,
                      # width = unit(25, "cm"), 
                       box.colour = NA) +
  scale_color_manual( values = c("IDP" = "#00B398",
                                 "OIP" = "#EF4A60",
                                 "ASY" = "#18375F",
                                 "REF" = "#0072BC",
                                 "OOC" = "#8395b9",
                                 "STA" = "#E1CC0D")) +
  xlim(c(0, 2)) +
  ylim(c(0, 3)) +
  facet_wrap(vars(fig), ncol = 2)  +
  labs(title = paste0("Key Figures for ", country_name_text, " as of ", year), 
       subtitle = paste0("A total of ",
                         format(round(total_poc, 0), scientific = FALSE, big.mark=","),
                         " people, ",
                        ifelse(perc_change_poc>0,"increasing", "decreasing" ) , 
                         " by ",  round(abs(perc_change_poc), 1), 
                         "% compared to the previous year"),
       caption = "Source: UNHCR.org/refugee-statistics") +
  unhcrthemes::theme_unhcr_map() +
  theme(strip.text.x = element_text(size = 14),
        legend.position = "none"
        )  
  return(p)

}
plot_ctr_keyfig(year = 2022,
                country_asylum_iso3c = "COL")
#test_that("plot_ctr_keyfig works", {  expect_true(inherits(plot_ctr_keyfig, "function")) })

Plot Tree Map of Categories

#' Tree map of Population Groups within a country
#'
#' @param year Numeric value of the year (for instance 2020)
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line 
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  scale_color_manual scale_colour_manual 
#'             geom_text
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace 
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty
#' @importFrom stats  reorder aggregate 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join
#' @importFrom tidyr pivot_longer
#' @importFrom unhcrthemes theme_unhcr
#' 
#' @return a ggplot2 object
#' 
#' @export
#'

plot_ctr_treemap <- function(year = 2021,
                             country_asylum_iso3c = country_asylum_iso3c) {

  country_name_text <- nansen::countries  |> 
    dplyr::filter(iso_code == country_asylum_iso3c) |>
    dplyr::distinct(name) |>
    dplyr::pull()

  datatree <- nansen::population |> 
  tidyr::pivot_longer(
    cols = refugees:hst,
    names_to = "population_type",
    values_to = "value"
  ) |> 
  dplyr::filter(year == year,
                coa_iso == country_asylum_iso3c) |>
   dplyr::select(-c(year)) |>
   dplyr::group_by(coa_name,  population_type) |>
   dplyr::summarise(across(where(is.numeric), ~sum(.x, na.rm = TRUE)), .groups = 'drop') |>
   dplyr::mutate(
   population_type_name = stringr::str_replace_all(population_type, pattern = dict_pop_type_name)
  )

  p <- ggplot() +
         treemapify::geom_treemap(data = datatree, 
                 aes(area = value, 
                     fill = population_type) ) +
         treemapify::geom_treemap_text(data = datatree, 
                     aes(area = value, 
                         fill = population_type,
                         label = paste0(round(100 * value / sum(value),1), 
                          "%\n", 
                          population_type_name) ),
                     colour = "white",
                           place = "centre", size = 25) +
         scale_fill_manual( values = c("idps" = "#00B398",
                                       # "VDA"="#EF4A60",
                                       "oip" = "#EF4A60",
                                       "asylum_seekers" = "#18375F",
                                       "refugees" = "#0072BC",
                                       "ooc" = "#8395b9",
                                       "stateless" = "#E1CC0D")) +

      unhcrthemes::theme_unhcr(font_size = 14,
                  grid = "Y", 
                  axis = "x", 
                  axis_title = "y", 
                  legend = FALSE) +
         theme(legend.position = "none") +
         ## and the chart labels

         labs(title = paste0("Population of Concern in ",  ctrylabel),
              subtitle = paste0(" As of ", year, ", a total of ", format(round(sum(datatree$Value), -3),  big.mark=","), " Individuals"),
              x = "",
              y = "",
              caption = "Source: UNHCR.org/refugee-statistics")  

   return(p)
}
# 
plot_ctr_treemap(year = 2021,
                 country_asylum_iso3c = "USA"
         )

Plot Population Type Over year

#' Graph of Population Type Over year
#'
#' @param year Numeric value of the year (for instance 2020)
#' @param lag Number of year to used as comparison base
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' @param pop_type Vector of character values. Possible population type 
#'                  (e.g.: REF, IDP, ASY, OIP, OIP, OOC, STA)
#' 
#' @import ggplot2              
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace 
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty
#' @importFrom stats  reorder aggregate 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join
#' @importFrom tidyr pivot_longer
#' @importFrom unhcrthemes theme_unhcr
#' 
#' @return a ggplot2 object
#'
#' @export
#'
#'

plot_ctr_population_type_per_year <- function(year = 2022,
                                              lag = 5, 
                                              country_asylum_iso3c = country_asylum_iso3c,
                                              pop_type = pop_type
                                     ) {



  cols_poptype <- c("Asylum-seekers" = "#18375F",
                    "Refugees" = "#0072BC",
                    #"Venezuelans Displaced Abroad" = "#EF4A60", 
                    "Other people in need of international protection" = "#EF4A60", 
                    "Others of Concern to UNHCR" = "#999999",
                    "Internally displaced persons" = "#00B398",
                    "Stateless Persons" = "#E1CC0D")


  df <- nansen::population  |>
    dplyr::filter(year  >= (!!year - lag) & year  <= !!year,  #### Parameter
         coa_iso == country_asylum_iso3c, #### Parameter
  )  |> 
  tidyr::pivot_longer(
    cols = refugees:hst,
    names_to = "population_type",
    values_to = "value"
  ) |>
   dplyr::mutate(
   population_type_label = stringr::str_replace_all(population_type, pattern = dict_pop_type_label)
  ) |> 
  dplyr::filter(
         population_type_label %in% pop_type #### Parameter
    )  |> 
     dplyr::group_by(year, coa_name,  population_type, population_type_label) |>
   dplyr::summarise(across(where(is.numeric), ~sum(.x, na.rm = TRUE)), .groups = 'drop') |> 
   dplyr::mutate(
   population_type_name = stringr::str_replace_all(population_type, pattern = dict_pop_type_name)
  ) 


  ## need to sort with so that the small value are on the top for better legibility 
  # levels(as.factor(df$population_type_label)) is alpha... 
  # let's sort based on value from this year
  df$population_type_name <- factor(df$population_type_name,
          levels =  unique(df$population_type_name[order(df$value)])
                                     )



  country_name_text <- df |>
    distinct(coa_name) |>
    pull()

  year_breaks <- diff(range(df$year)) + 1 

  p <- ggplot() +
    geom_col( data = df, 
             aes(x = year, 
                 y = value, 
                 fill = population_type_name),
             width = 0.7) +

    ## Need some conditions to put labels or not o the chart - to avoid cluttered
    # chart.. 

    geom_text(data = df |>filter(value > mean(df$value) *0.1), 
             aes(x = year, 
                  y = value, 
                  color = population_type_name, 
                  label = label_number(accuracy = .1,
                                   scale_cut = cut_short_scale())(value)),
              position = position_stack(vjust = 0.5),
              show.legend = FALSE,
              size = 5) +
    ## This add the total on the top of the chart..
    stat_summary(data = df, 
                  fun = sum, 
                 aes(x = year,
                     y = value, 
                     label = scales::label_number(accuracy = .1,
                                          scale_cut = cut_short_scale())(after_stat(y)),
                     group = year), 
                 geom = "text", size = 5,    vjust = -0.5) +
    scale_color_manual(values = c("#FFFFFF",
                                  "#FFFFFF",
                                  "#FFFFFF",
                                  "#FFFFFF",
                                  "#FFFFFF",
                                  "#FFFFFF")) +
    scale_fill_manual(values = cols_poptype,
                      drop = TRUE,
                      limits = force) +
    scale_x_continuous(breaks = scales::breaks_pretty(n = year_breaks)) +
    scale_y_continuous(expand = expansion(c(0, 0.1))) +
    labs(title = paste0(country_name_text, ": Population Type per year"), 
         subtitle = "Number of people (thousand)",
         caption = "Source: UNHCR.org/refugee-statistics") +
    theme_unhcr(grid = FALSE, axis = "x", 
                axis_title = FALSE, axis_text = "x",
              font_size = 14) +

    theme(legend.direction = "horizontal",
          legend.position = "bottom",
          legend.text=element_text(size = rel(0.5)),
          legend.key.size = unit(0.8, 'cm'),
          text = element_text(size = 20),
          plot.subtitle=element_text(size=19),
          plot.title = element_text(size=23),
          plot.caption = element_text(size=13))

  return(p) # print(p)
  }
p <- plot_ctr_population_type_per_year(
                         year = 2018,
                         country_asylum_iso3c = "BRA",
                         lag = 5,
                         pop_type = c("REF", 
                                       "ASY", 
                                       "OIP", 
                                       "OOC",
                                       "STA",
                                       "IDP" )
                  )
p
## Raw data can always be accessed with 
#knitr::kable(ggplot2::ggplot_build(p)$plot$data )
# test_that("The function creates a plot", {
#   expect_true(is.ggplot(plot_ctr_population_type_per_year()))
# })

# test_that("The function takes the correct parameters", {
#   expect_equal(plot_ctr_population_type_per_year(year = 2022,
#                                                 lag = 5, 
#                                                 country_asylum_iso3c = country_asylum_iso3c,
#                                                 pop_type = Population.type),
#                plot_ctr_population_type_per_year())
# })

2. Origin

Plot Main country of origin in one specific country - Absolute value

#' Main country of origin - Absolute value
#'
#' @param year Numeric value of the year (for instance 2020)
#' 
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' 
#' @param top_n_countries Numeric value of number of main countries that the graph should display
#' 
#' @param pop_type Character value. Possible population type (e.g.: REF, IDP, ASY,   OIP, OOC, STA)
#' 
#' @param show_diff_label logical to indicate whether or not adding the the label displaying difference in percentage compared to the previous year
#' 
#' 
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  scale_color_manual scale_colour_manual 
#'             geom_text
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace 
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty
#' @importFrom stats  reorder aggregate 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join
#' @importFrom tidyr pivot_longer
#' @importFrom unhcrthemes theme_unhcr
#' 
#' @return a ggplot2 object
#' 
#' @export
#'

plot_ctr_population_type_abs <- function(year = 2021,
                                         country_asylum_iso3c = country_asylum_iso3c,
                                         top_n_countries = 9,
                                         pop_type = "REF",
                                         show_diff_label = TRUE
) {




  cols_poptype <- list(ASY = c("Asylum-seekers", "#18375F"),
                       REF = c("Refugees", "#0072BC"),
                       #VDA = c("Venezuelans Displaced Abroad", "#EF4A60"), 
                       OIP = c("Other people in need of international protection", "#EF4A60"), 
                       OOC = c("Others of Concern to UNHCR", "#999999"),
                       IDP = c("Internally displaced persons", "#00B398"),
                       STA = c("Stateless Persons", "#E1CC0D")
  )



   df <- nansen::population  |>
    dplyr::filter(
           (year == !!year | year == !!year - 1),  #### Parameter
           coa_iso == country_asylum_iso3c, #### Parameter
  )  |> 
  tidyr::pivot_longer(
    cols = refugees:hst,
    names_to = "population_type",
    values_to = "value"
  ) |> 
   dplyr::mutate(
   population_type_label = stringr::str_replace_all(population_type, pattern = dict_pop_type_label)
  ) |> 
  dplyr::filter(
         population_type_label %in% pop_type, #### Parameter
         value != 0 | is.na(value)) |>
   dplyr::group_by(year, coa_name, coo_name, population_type, population_type_label) |>
   dplyr::summarise(across(where(is.numeric), ~sum(.x, na.rm = TRUE)), .groups = 'drop') |> 
   dplyr::mutate(
   population_type_name = stringr::str_replace_all(population_type, pattern = dict_pop_type_name)
  ) |>
    group_by(coa_name, coo_name) |>
    arrange(year) |>

    mutate(diff_pop_type_value = label_percent(accuracy = 0.1,
                                                trim = FALSE) (((value-lag(value))/lag(value)))  ) |>
    ungroup() |>
    filter(year == !!year) |>
    mutate(
      origin_data_prot = forcats::fct_lump_n(
        f = coo_name,
        n = top_n_countries,  #### Parameter
        w = value,
        other_level = 'Other nationalities',
        ties.method = "last"
      )
    ) |>
    mutate(origin_data_prot = forcats::fct_na_value_to_level(origin_data_prot,
                                                       'Other nationalities'),
           diff_pop_type_value = case_when(origin_data_prot == 'Other nationalities' ~ "",
                                           TRUE ~ diff_pop_type_value)) |>
    group_by(coa_name, diff_pop_type_value, origin_data_prot) |>
    summarise(value = sum(value, na.rm = TRUE), .groups = 'drop') |>
    ungroup() |>
    arrange(desc(value)) |>
    filter(value != 0L) |>
    mutate(
      origin_data_prot = forcats::fct_rev(forcats::fct_inorder(origin_data_prot)),
      origin_data_prot =  suppressWarnings(
        case_when(
          origin_data_prot == "Other nationalities" ~ forcats::fct_relevel(origin_data_prot,
                                                                           "Other nationalities",
                                                                           after = 0),
          TRUE ~ origin_data_prot
        )
      ),
      perc = label_percent(
        accuracy = 1,
        trim = TRUE
      )(value / sum(value))
    )

  country_name_text <- df |>
    distinct(coa_name) |>
    pull()


  p <- ggplot() +
    geom_col(data = df, 
             aes(x = value, y = origin_data_prot),
             fill = cols_poptype_label[[pop_type]][1],
             width = 0.8) +
    ## Position label differently in the bar in white - outside bar in black
    geom_text(
      data = subset(df, value < max(value) / 1.5),
      aes(
        x = value,
        y = origin_data_prot,
        label = label_number(accuracy = 1,
                             scale_cut = cut_short_scale())(value)
      ),
      hjust = -0.1 ,
      vjust = 0.5,
      colour = "black",
      size = 6
    ) +
    geom_text(
      data = subset(df, value >= max(value) / 1.5),
      aes(
        x = value,
        y = origin_data_prot,
        label = label_number(accuracy = 1,
                             scale_cut = cut_short_scale())(value)),
      hjust = 1.1 ,
      vjust = 0.5,
      colour = "white",
      size = 6
    ) 

  # Add diff labels
  if(show_diff_label == TRUE) {
    # diff label positive general
    p <- p + geom_text( 
      data = subset(df, with(df, grepl('^[0-9]', diff_pop_type_value)) & (value < max(value) / 1.5)),
      aes(
        x = value,
        y = origin_data_prot,
        label = paste(intToUtf8(9650), diff_pop_type_value)
      ),
      hjust = -1.2,
      vjust = 0.5,
      colour = "grey",
      size = 5
    ) +
    # diff label negative general
    geom_text(
      data = subset(df, with(df, grepl('-', diff_pop_type_value)) & (value < max(value) / 1.5)),
      aes(
        x = value,
        y = origin_data_prot,
        label = paste(intToUtf8(9660), diff_pop_type_value)
      ),
      hjust = -1.2,
      vjust = 0.5,
      colour = "#0472bc",
      size = 5
    ) +
  # diff label positive max
    geom_text(
      data = subset(df, with(df, grepl('^[0-9]', diff_pop_type_value)) & (value >= max(value) / 1.5)),
      aes(
        x = value,
        y = origin_data_prot,
        label = paste(intToUtf8(9650), diff_pop_type_value)
      ),
      hjust = -0.4,
      vjust = 0.5,
      colour = "grey",
      size = 5
    ) +
  # diff label negative max
    geom_text(
      data = subset(df, with(df, grepl('-', diff_pop_type_value)) & (value >= max(value) / 1.5)),
      aes(
        x = value,
        y = origin_data_prot,
        label = paste(intToUtf8(9660), diff_pop_type_value)
      ),
      hjust = -0.4,
      vjust = 0.5,
      colour = "#0472bc",
      size = 5
    )} 

  p <- p + 
    labs(title = paste0(country_name_text, ": ", stringr::str_to_title(names(dict_pop_type_label[dict_pop_type_label==pop_type])) , " | ",  year),
         subtitle = paste0("Top ",  top_n_countries, " Countries of Origin"),
         x = "Number of People",
         caption = "Source: UNHCR.org/refugee-statistics") +
    scale_x_continuous(expand = expansion(c(0, 0.1))) +
    theme_unhcr(grid = FALSE, axis = "y", 
                axis_title = FALSE, axis_text = "y",
                font_size = 14) +
    theme(legend.direction = "vertical",
          legend.key.size = unit(0.8, 'cm'),
          text = element_text(size = 20),
          plot.subtitle=element_text(size=19),
          plot.title = element_text(size=23),
          plot.caption = element_text(size=13))

  return(p) 
}
plot_ctr_population_type_abs(year = 2020,
                    country_asylum_iso3c = "USA",
                    top_n_countries = 4,
                    pop_type = "REF",
                    show_diff_label = FALSE
                    ) 

## Same with 9 top countries and Asylum-seekers included
plot_ctr_population_type_abs(year = 2020,
                    country_asylum_iso3c = "USA",
                    top_n_countries = 9,
                    pop_type = "ASY",
                    show_diff_label = TRUE
                    ) 

Plot Main country of origin in one specific country - Percentage

#' Main country of origin - Percentage
#'
#' @param year Numeric value of the year (for instance 2020)
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' @param top_n_countries Numeric value of number of main countries that the graph should display
#' @param pop_type Character value. Possible population type (e.g.: REF, IDP, ASY, OIP, OOC, STA)
#' 
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  scale_color_manual scale_colour_manual 
#'             geom_text
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace 
#' @importFrom scales cut_short_scale percent label_number breaks_pretty
#' @importFrom stats  reorder aggregate 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join
#' @importFrom tidyr pivot_longer
#' @importFrom unhcrthemes theme_unhcr
#' 
#' @return a ggplot2 object
#' 
#' @export
#'

plot_ctr_population_type_perc <- function(year = 2021,

                                country_asylum_iso3c = country_asylum_iso3c,
                                top_n_countries = 9,
                                pop_type = "REF"
                              ) {



  cols_poptype <- list(ASY = c("Asylum-seekers", "#18375F"),
                       REF = c("Refugees", "#0072BC"),
                      # VDA = c("Venezuelans Displaced Abroad", "#EF4A60"), 
                       OIP = c("Other people in need of international protection", "#EF4A60"), 
                       OOC = c("Others of Concern to UNHCR", "#999999"),
                       IDP = c("Internally displaced persons", "#00B398"),
                       STA = c("Stateless Persons", "#E1CC0D")
  )



   df <- nansen::population  |>
    dplyr::filter(
           (year == !!year | year == !!year - 1),  #### Parameter
           coa_iso == country_asylum_iso3c, #### Parameter
  )  |> 
  tidyr::pivot_longer(
    cols = refugees:hst,
    names_to = "population_type",
    values_to = "value"
  ) |> 
   dplyr::mutate(
   population_type_label = stringr::str_replace_all(population_type, pattern = dict_pop_type_label)
  ) |> 
  dplyr::filter(
         population_type_label %in% pop_type, #### Parameter
         value != 0 | is.na(value)) |>
   dplyr::group_by(year, coa_name, coo_name, population_type, population_type_label) |>
   dplyr::summarise(across(where(is.numeric), ~sum(.x, na.rm = TRUE)), .groups = 'drop') |> 
   dplyr::mutate(
   population_type_name = stringr::str_replace_all(population_type, pattern = dict_pop_type_name)
  ) |>
    group_by(coa_name, coo_name) |>
    arrange(year) |>
    mutate(diff_pop_type_value = label_percent(accuracy = 0.1,
                                                trim = FALSE) (((value-lag(value))/lag(value)))  ) |>
    ungroup() |>
    filter(year == !!year) |>
    mutate(
      origin_data_prot = forcats::fct_lump_n(
        f = coo_name,
        n = top_n_countries,  #### Parameter
        w = value,
        other_level = 'Other nationalities',
        ties.method = "last"
      )
    ) |>
    mutate(origin_data_prot = forcats::fct_na_value_to_level(origin_data_prot,
                                                       'Other nationalities'),
           diff_pop_type_value = case_when(origin_data_prot == 'Other nationalities' ~ "",
                                           TRUE ~ diff_pop_type_value)) |>
    group_by(coa_name, diff_pop_type_value, origin_data_prot) |>
    summarise(value = sum(value, na.rm = TRUE), .groups = 'drop') |>
    ungroup() |>
    arrange(desc(value)) |>
    filter(value != 0L) |>
    mutate(
      origin_data_prot = forcats::fct_rev(forcats::fct_inorder(origin_data_prot)),
      origin_data_prot =  suppressWarnings(
        case_when(
          origin_data_prot == "Other nationalities" ~ forcats::fct_relevel(origin_data_prot,
                                                                           "Other nationalities",
                                                                           after = 0),
          TRUE ~ origin_data_prot
        )
      ),
      perc = label_percent(
        accuracy = 1,
        trim = FALSE
      )(value / sum(value))
    )

  country_name_text <- df |>
    distinct(coa_name) |>
    pull()


  p <- ggplot() +
    geom_col(data = df, 
             aes(x = value, y = origin_data_prot),
             fill = cols_poptype_label[[pop_type]][1],
             width = 0.8) +
    ## Position label differently in the bar in white - outside bar in black
    geom_text(
      data = subset(df, value < max(value) / 1.5),
      aes(
        x = value,
        y = origin_data_prot,
        label = perc
      ),
      hjust = -0.1 ,
      vjust = 0.5,
      colour = "black",
      size = 6
    ) +
    geom_text(
      data = subset(df, value >= max(value) / 1.5),
      aes(
        x = value,
        y = origin_data_prot,
        label = perc),
      hjust = 1.1 ,
      vjust = 0.5,
      colour = "white",
      size = 6
    ) 

  # Add diff labels
  if(show_diff_label == TRUE) {
    # diff label positive general
    p <- p + geom_text( 
      data = subset(df, with(df, grepl('^[0-9]', diff_pop_type_value)) & (value < max(value) / 1.5)),
      aes(
        x = value,
        y = origin_data_prot,
        label = paste(intToUtf8(9650), diff_pop_type_value)
      ),
      hjust = -1.2,
      vjust = 0.5,
      colour = "grey",
      size = 5
    ) +
    # diff label negative general
    geom_text(
      data = subset(df, with(df, grepl('-', diff_pop_type_value)) & (value < max(value) / 1.5)),
      aes(
        x = value,
        y = origin_data_prot,
        label = paste(intToUtf8(9660), diff_pop_type_value)
      ),
      hjust = -1.2,
      vjust = 0.5,
      colour = "#0472bc",
      size = 5
    ) +
  # diff label positive max
    geom_text(
      data = subset(df, with(df, grepl('^[0-9]', diff_pop_type_value)) & (value >= max(value) / 1.5)),
      aes(
        x = value,
        y = origin_data_prot,
        label = paste(intToUtf8(9650), diff_pop_type_value)
      ),
      hjust = -0.4,
      vjust = 0.5,
      colour = "grey",
      size = 5
    ) +
  # diff label negative max
    geom_text(
      data = subset(df, with(df, grepl('-', diff_pop_type_value)) & (value >= max(value) / 1.5)),
      aes(
        x = value,
        y = origin_data_prot,
        label = paste(intToUtf8(9660), diff_pop_type_value)
      ),
      hjust = -0.4,
      vjust = 0.5,
      colour = "#0472bc",
      size = 5
    )} 

  p <- p + 
    labs(title = paste0(country_name_text, ": ", stringr::str_to_title(names(dict_pop_type_label[dict_pop_type_label==pop_type])) , " | ",  year),
         subtitle = paste0("Top ",  top_n_countries, " Countries of Origin"),
         x = "Number of People",
         caption = "Source: UNHCR.org/refugee-statistics") +
    scale_x_continuous(expand = expansion(c(0, 0.1))) +
    theme_unhcr(grid = FALSE, axis = "y", 
                axis_title = FALSE, axis_text = "y",
                font_size = 14) +
    theme(legend.direction = "vertical",
          legend.key.size = unit(0.8, 'cm'),
          text = element_text(size = 20),
          plot.subtitle=element_text(size=19),
          plot.title = element_text(size=23),
          plot.caption = element_text(size=13))

  return(p) 
}
plot_ctr_population_type_perc(year = 2021,
                    country_asylum_iso3c = "BRA",
                    top_n_countries = 9,
                    pop_type = "REF",
                    show_diff_label = FALSE) 

plot_ctr_population_type_perc(year = 2021,
                    country_asylum_iso3c = "BRA",
                    top_n_countries = 9,
                    pop_type = "ASY",
                    show_diff_label = TRUE) 

Plot Increases and Decreases in Population Groups

#' Increases and Decreases in Population Groups
#'
#' @param year Numeric value of the year (for instance 2020)
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' @param pop_type Vector of character values. Possible population type (e.g.: REF, IDP, ASY, OIP, OOC, STA)
#' 
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  scale_color_manual scale_colour_manual 
#'             geom_text
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace 
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty
#' @importFrom stats  reorder aggregate 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join
#' @importFrom tidyr pivot_longer  gather separate spread
#' @importFrom unhcrthemes theme_unhcr
#' 
#' @return a ggplot2 object
#' 
#' @export
#'

plot_ctr_diff_in_pop_groups <- function(year = 2021,
                                        country_asylum_iso3c = country_asylum_iso3c,
                                        pop_type = pop_type
) {



  # diff_perc <- function(x){
  #   x = as.numeric((x - lag(x))/lag(x)) + 0
  #   
  # }
#  \(x) as.numeric((x - lag(x))/lag(x)) + 0

  df <- ForcedDisplacementStat::end_year_population_totals  |>
    filter(CountryAsylumCode != "UKN",
           !is.na(CountryAsylumCode),
           (Year == year-1 | Year == year),  #### Parameter
           CountryAsylumCode == country_asylum_iso3c #### Parameter
    ) |>
    group_by(Year, CountryAsylumName) |>
    summarise(across(where(is.numeric), sum)) |>
    ungroup() |>
    arrange(Year) |>
    select(-c(Year)) |>
    group_by(CountryAsylumName) |>
    summarise(across(where(is.numeric), 
                     list(diffabs = diff,

                         # diffperc = diff_perc),
                          diffper = \(x) as.numeric((x - lag(x))/lag(x)) + 0 ),

                     .names = "{.col}_{.fn}")) |> 
    ungroup() |>  
    slice(2) 

  df <- replace(df, is.na(df), 0)

  df <- df |> 
    tidyr::gather(v, value, REF_diffabs:HCO_diffper) |> 
    tidyr::separate(v, c("population_type", "value_type"), sep = "\\_") |> 
    tidyr::spread(key = value_type, value = value) 


  df <- df |>         
 mutate(diffper = label_percent(accuracy = 1,  trim = FALSE) (diffper))
   #    mutate(diffper = label_percent(accuracy = 1,  trim = FALSE) (\(x) as.numeric((x - lag(x))/lag(x)) + 0 ))



  df <- df |>
    filter(population_type %in% pop_type)

  p <- ggplot() +
    geom_col(data = df, 
           aes(x = population_type, 
                 y = diffabs,
                 fill = population_type),
             width = 0.8) +
    scale_fill_manual(
      values = c("ASY" = "#18375F",
                 "REF" = "#0072BC",
                 "OIP" = "#EF4A60", 
                 #"VDA" = "#EF4A60", 
                 "OOC" = "#999999",
                 "IDP" = "#00B398",
                 "STA" = "#E1CC0D"),
      drop= TRUE, limits = force, guide="none"    ) +
    scale_x_discrete(labels= c("ASY" = "Asylum-seekers",
                               "REF" = "Refugees",
                               #"VDA" = "Venezuelans Displaced\nAbroad", ,
                               "OIP" = "Other people in need\n of international protection", 
                               "OOC" = "Others of Concern\nto UNHCR",
                               "IDP" = "Internally Displaced\nPersons",
                               "STA" = "Stateless Persons"),
                     drop = TRUE,
                     limits = force) +

    ## Adding labels with conditionned positions...

    geom_text(  data = subset(df, diffabs >= 0 & diffabs < max(diffabs) / 1.5),
                aes(x = population_type,
                    y = diffabs,
                    label = label_number(accuracy = 1,
                                         scale_cut = cut_short_scale())(diffabs)),
                vjust = -0.5 , colour = "black", size = 5   ) +

    geom_text( data = subset(df, diffabs >= 0 & diffabs < max(diffabs) / 1.5),
               aes(  x = population_type,
                     y = diffabs,
                     label = paste(intToUtf8(9650), diffper)),
               vjust = -2.0 , colour = "black", size = 5  ) +

    geom_text( data = subset(df, diffabs >= 0 & diffabs >= max(diffabs) / 1.5),
               aes(  x = population_type,
                     y = diffabs,
                     label = label_number(accuracy = 1,
                                          scale_cut = cut_short_scale())(diffabs) ),
               vjust = 2.7 ,   colour = "white",   size = 5  ) + 

    geom_text(  data = subset(df, diffabs >= 0 & diffabs >= max(diffabs) / 1.5),
                aes(x = population_type,
                    y = diffabs,
                    label = paste(intToUtf8(9650), diffper)),
                vjust = 1.2 ,   colour = "white",   size = 5    ) + 

    geom_text( data = subset(df, diffabs < 0/ 1.5),
               aes(  x = population_type,
                     y = diffabs,
                     label = label_number(accuracy = 1,
                                          scale_cut = cut_short_scale())(diffabs)),
               vjust =  1.2, colour = "black", size = 5  ) +

    geom_text( data = subset(df, diffabs < 0  / 1.5),
               aes( x = population_type,
                    y = diffabs,
                    label = paste(intToUtf8(9660), diffper)),
               vjust = 2.7,  colour = "black",  size = 5  ) +

    geom_hline(yintercept = 0, color = "black") +

    labs(title = paste0(df |>
                          distinct(CountryAsylumName) |>
                          pull(), 
                        ": Increases and Decreases in Population Groups | ",
                        year-1,
                        "-",
                        year),
         subtitle = "Number of people and percentage",
         caption = "Source: UNHCR.org/refugee-statistics")  + 
    theme_unhcr(grid = FALSE, axis = "x",
                axis_title = FALSE, axis_text = "x",
                font_size = 14) +
    theme(axis.line.x = element_line(color="white"),
          axis.text.x = element_text(size=10))

  # geom_text(
  #   data = subset(df, diffabs < 0 & diffabs <= min(diffabs) / 1.5),
  #   aes(
  #     x = population_type,
  #     y = diffabs,
  #     label = label_number(accuracy = 1,
  #                                  scale_cut = cut_short_scale())(diffabs)
  #   ),
  #   vjust = -2.0 ,
  #   colour = "white",
  #   size = 5
  # )  +
  #   geom_text(
  #     data = subset(df, diffabs < 0 & diffabs <= min(diffabs) / 1.5),
  #     aes(
  #       x = population_type,
  #       y = diffabs,
  #       label = diffper
  #     ),
  #     vjust = -0.5 ,
  #     colour = "white",
  #     size = 5
  #   ) +


  return(p) # print(p)
}
# 
plot_ctr_diff_in_pop_groups(year = 2022,
                            country_asylum_iso3c = "ROU",
                            pop_type = c("REF", "ASY")
         )

Plot Origin History

#' Plot Origin History
#' 
#' The functions gives a quick overview of the main source of displacement in terms of origin in the country
#' 
#' @param year Numeric value of the year (for instance 2020)
#' @param lag Number of year to used as comparison base
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' @param pop_type Vector of character values. Possible population type (e.g.: REF, IDP, ASY, OIP, OIP, OOC, STA)
#' @param otherprop value set by default to .02 - used to merge origin as "Other"
#' 
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  scale_color_manual scale_colour_manual 
#'             geom_text scale_fill_brewer scale_colour_brewer
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace 
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty
#' @importFrom stats  reorder aggregate 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join
#' @importFrom ggalluvial geom_alluvium
#' @importFrom unhcrthemes theme_unhcr
#' 
#' @return a ggplot2 object
#'
#' @export

plot_ctr_origin_history <- function(year = 2022,
                                     lag = 5, 
                                     country_asylum_iso3c = country_asylum_iso3c,
                                     pop_type = Population.type,
                                     otherprop = .02
                                     ) {



  df <- ForcedDisplacementStat::end_year_population_totals_long  |>
          filter(       year >= (year - lag),  #### Parameter
                        CountryAsylumCode == country_asylum_iso3c, #### Parameter
                        Population.type %in% pop_type #### Parameter
          )  |>   
          dplyr::mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = otherprop, w = value)) |>
          group_by(year, CountryAsylumName, CountryOriginName)  |>
          summarise(value = sum(value, na.rm = TRUE)) |>
          ungroup()

  country_name_text <- df |>
    distinct(CountryAsylumName) |>
    pull()

  year_breaks <- diff(range(df$year)) + 1 

  p <- ggplot() +
  ggalluvial::geom_alluvium(data = df,
       aes(x = year, 
           y = value, 
           alluvium = CountryOriginName,
           fill = CountryOriginName, 
           colour = CountryOriginName),
                            alpha = .75, 
                            decreasing = FALSE) +
  scale_x_continuous(breaks = seq(year-lag, year, 2)) +  
  scale_y_continuous(expand = expansion(c(0, 0.1)),
                     labels = label_number(scale_cut = cut_short_scale())) +
  theme_unhcr(grid = TRUE, axis = "x", 
              axis_title = TRUE, #axis_text = "x",
              font_size = 14) +
  theme(axis.text.x = element_text(angle = -30, hjust = 0)) +
  scale_fill_brewer(type = "qual", palette = "Set3") +
  scale_colour_brewer(type = "qual", palette = "Set3") +
  # facet_wrap(~ region, scales = "fixed") ++
  labs(title = paste0(country_name_text, ":  Evolution of Forcibly Displaced Population Origin"), 
       subtitle = "Number of people (thousand)",
       x = "", y = "",
       caption = "Source: UNHCR.org/refugee-statistics")

  return(p) # print(p)
  }
plot_ctr_origin_history(year = 2022,
                        lag = 5,
                        country_asylum_iso3c = "MEX",
                          pop_type = c("REF", 
                                       "ASY", 
                                       "OIP", 
                                       "IDP" ),
                        otherprop = .02)
#test_that("plot_ctr_origin_history works", {   expect_true(inherits(plot_ctr_origin_history, "function")) })

3. Destination

Plot Main Destination from one specific country

#' Main Destination from  one specific countr
#'
#' @param year Numeric value of the year (for instance 2020)
#' @param country_origin_iso3c Character value with the ISO-3 character code of the Country of Origin
#' @param pop_type Vector of character values. Possible population type (e.g.: REF, IDP, ASY, OIP, OOC, STA)
#' 
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  scale_color_manual scale_colour_manual 
#'             geom_text theme_void
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace 
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty
#' @importFrom stats  reorder aggregate 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join
#' @importFrom tidyr pivot_longer
#' @importFrom unhcrthemes theme_unhcr
#' 
#' @return a ggplot2 object
#' 
#' @export
#'

plot_ctr_destination <- function(year = 2021,
                                 country_origin_iso3c = country_origin_iso3c,
                                 pop_type = pop_type) {

  country_name_text <- ForcedDisplacementStat::reference |>
    filter(iso_3 == country_origin_iso3c) |>
    select(ctryname) |>
    pull()

  Destination <-
    left_join(
      x = ForcedDisplacementStat::end_year_population_totals_long,
      y = ForcedDisplacementStat::reference,
      by = c("CountryAsylumCode" = "iso_3")
    )  |>
    filter(
      CountryOriginCode  == country_origin_iso3c  &
        year == year &
        Population.type  %in% as.vector(pop_type)
    )  |>
    mutate(
      CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
      CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
      CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
      CountryAsylumName = str_replace(
        CountryAsylumName,
        "United Kingdom of Great Britain and Northern Ireland",
        "UK"
      )
    ) |>
    group_by(CountryAsylumName) |>
    summarise(DisplacedAcrossBorders = sum(value))  |>
    mutate(DisplacedAcrossBordersRound =  ifelse(
      DisplacedAcrossBorders > 1000,
      paste(
        label_number(accuracy = .1,
                     scale_cut = cut_short_scale())(DisplacedAcrossBorders)
      ),
      as.character(DisplacedAcrossBorders)
    )) |>
    arrange(desc(DisplacedAcrossBorders)) |>
    head(10) |>
    filter(DisplacedAcrossBorders > 0)

  if(nrow(Destination) ==  0) {

    info <-  paste0("There\'s no recorded Countries of destination \n in ", ForcedDisplacementStat::reference |>
             dplyr::filter( iso_3 == country_origin_iso3c) |>
             dplyr::pull(ctryname) , " for ", year)
    p <- ggplot() +  annotate(stringr::str_wrap("text", 80), 
                              x = 1, y = 1, size = 11,  
                              label = info ) +  theme_void() 

  } else {
    #Make plot
    p <-  ggplot() +
          geom_col(data = Destination, 
                aes(
                x = reorder(CountryAsylumName, DisplacedAcrossBorders),
                ## Reordering country by value
                y = DisplacedAcrossBorders),
               fill = unhcr_pal(n = 1, "pal_blue")) + # here we configure that it will be bar chart+
        ## Format axis number
       scale_y_continuous(expand = expansion(c(0, 0.1)),
                     labels = label_number(scale_cut = cut_short_scale())) +
        ## Position label differently in the bar in white - outside bar in black
        geom_label(
          data = subset(
            Destination,
            DisplacedAcrossBorders < max(DisplacedAcrossBorders) / 1.5
          ),
        aes(
          x = reorder(CountryAsylumName, DisplacedAcrossBorders),
          y = DisplacedAcrossBorders,
          label = DisplacedAcrossBordersRound
        ),
        hjust = -0.1 ,
        vjust = 0.5,
        colour = "black",
        fill = NA,
        label.size = NA,
        #family = "Lato",
        size = 4
      ) +

      geom_label(
        data = subset(
          Destination,
          DisplacedAcrossBorders >= max(DisplacedAcrossBorders) / 1.5
        ),
        aes(
          x = reorder(CountryAsylumName, DisplacedAcrossBorders),
          y = DisplacedAcrossBorders,
          label = DisplacedAcrossBordersRound
        ),
        hjust = 1.1 ,
        vjust = 0.5,
        colour = "white",
        fill = NA,
        label.size = NA,
        # family = "Lato",
        size = 4
      ) +
      # Add `coord_flip()` to make your vertical bars horizontal:
      coord_flip() +

      ## and the chart labels
      labs(
        title = paste0("What are the main destinations for Forcibly Displaced People?"),

        subtitle = paste0(
          "Top Destination Countries | as of ",
          year,
          " for population from ",
          country_name_text
        ),
        x = "",
        y = "",
        caption = "Source: UNHCR Population Statistics Database.\n Forced Displacement includes Refugees, Asylum-seekers and Other in Need of International Protection."
      ) +
    theme_unhcr(font_size = 14,
                  grid = FALSE,
                  axis = "y",
                  axis_title = FALSE,
                  axis_text = "y"
                )


  }
  return(p) # print(p)
}
# 
plot_ctr_destination(year = 2021,
                     country_origin_iso3c = "COL",
                     pop_type = c("REF", "ASY")
         )

plot recognition rate for a nationality

#' Display A Chart with Refugee Recognition Rate for nationals from a specific country
#' 
#' In the absence of an internationally agreed methodology for calculating recognition rates,
#'  UNHCR uses two rates to compute the proportion of refugee claims accepted during the year: 
#'  
#'   * The Refugee Recognition Rate divides the number of asylum-seekers granted Convention refugee
#'   status by the total number of accepted (Convention and, where relevant, complementary 
#'   protection) and rejected cases (aka substantive decision). 
#'   
#'   * The Total Recognition Rate divides the number of asylum-seekers granted Convention
#'    refugee status and / or complementary form of protection by the total number
#'    of accepted (Convention and, where relevant, complementary protection) and
#'     rejected cases.
#'     
#' Non-substantive decisions are, to the extent possible, excluded from both 
#' calculations. For the purpose of international comparability,  UNHCR only 
#' uses these two recognition rates and does not report nationally calculated rates.
#'      
#'      See https://www.unhcr.org/4ce531e09.pdf
#' 
#' @param year Numeric value of the year (for instance 2020)
#' @param country_origin_iso3c Character value with the ISO-3 character code of the Country of Origin
#' @param top_n_countries Numeric value of number of main countries that the graph should display
#' @param measure this can be either:
#'            * RefugeeRecognitionRate 
#'            * TotalRecognitionRate
#' @param order_by this can be either:
#'            * Recognized  
#'            * ComplementaryProtection  
#'            * TotalDecided 
#'            
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  scale_color_manual scale_colour_manual 
#'             geom_text guide_axis facet_wrap vars
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace 
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty pretty_breaks
#' @importFrom stats  reorder aggregate 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join
#' @importFrom tidyr pivot_longer
#' @importFrom unhcrthemes theme_unhcr  scale_fill_unhcr_d
#' 
#' @return a ggplot2 object
#' 
#' @export
plot_ctr_origin_recognition <- function(year = 2022,
                                 country_origin_iso3c  ,
                                 top_n_countries = 10, 
                                 measure = "RefugeeRecognitionRate",
                                 order_by = "TotalDecided" ){

   country_name_text <- ForcedDisplacementStat::reference |>
                 filter(iso_3 == country_origin_iso3c ) |>
               select(ctryname) |>
                pull()


   measurelabel <-
     dplyr::case_when(
       measure == "RefugeeRecognitionRate"  ~ "Refugee Recognition Rate",
       measure == "TotalRecognitionRate"  ~ "Total Recognition Rate"
     )

   order_bylabel <-
     dplyr::case_when(
       order_by == "Recognized"  ~ "Recognized Refugee Status Decisions",
       order_by == "ComplementaryProtection"  ~ "Complementary Protection Decisions",
       order_by == "TotalDecided"  ~ "Total Decision (independently of the outcome)"
     )

   topAsylum <-  ForcedDisplacementStat::asylum_decisions |>
     filter(CountryOriginCode == country_origin_iso3c &
              year == year) |>
     ## the below is change - DecisionsAveragePersonsPerCase- is just indicative... so no need to use it to m
     # mutate(DecisionsAveragePersonsPerCase = map_dbl(DecisionsAveragePersonsPerCase, ~replace_na(max(as.numeric(.), 1), 1))) |>
     mutate(DecisionsAveragePersonsPerCase = 1) |>
     group_by(CountryAsylumName) |>
     summarize(
       Recognized = sum(Recognized * DecisionsAveragePersonsPerCase, na.rm = TRUE),
       ComplementaryProtection = sum(
         ComplementaryProtection * DecisionsAveragePersonsPerCase,
         na.rm = TRUE
       ),
       TotalDecided = sum(TotalDecided * DecisionsAveragePersonsPerCase, na.rm = TRUE)
     ) |>
     mutate(
       RefugeeRecognitionRate = (Recognized) / TotalDecided,
       TotalRecognitionRate = (Recognized + ComplementaryProtection) / TotalDecided
     )   

   topAsylum1 <-  topAsylum  |>
     mutate(measured = .data[[measure]])  |>
     mutate(order_by = .data[[order_by]])  |>
     arrange(desc(order_by)) |>
     head(top_n_countries)   




   rsdAsylum <- ggplot() +
     geom_bar(data = topAsylum1, 
              aes(y = measured ,
                  x = reorder(CountryAsylumName, measured)),
              stat = "identity", fill = "#0072bc") +
     coord_flip() +
     #scale_y_continuous( labels = scales::label_number(accuracy = 1,   scale_cut = cut_short_scale())) + ## Format axis number
     scale_y_continuous( labels =   scales::label_percent(accuracy = 0.1, suffix = "%")) +

     #facet_grid(.~ ctry_asy) +
     #  geom_hline(yintercept = 0, size = 1.1, colour = "#333333")   +
     labs(
       title = paste0(measurelabel, " | ", year, " for Nationals from ", country_name_text),
       caption = 'Source: UNHCR.org/refugee-statistics ',
       subtitle = paste0(
         "For top ",
         top_n_countries,
         " Countries of Asylum ordered by ",
         order_bylabel
       ),
       x = " ",  y = " " ) +
     theme_unhcr(
       grid = "Y",
       axis = "x",
       axis_title = "" ,
       font_size = 14
     ) +
     theme(#axis.text.x = element_blank(),
       # legend.position = "none",

       panel.grid.major.x = element_line(color = "#cbcbcb"),
       panel.grid.major.y = element_blank()) ### changing grid line that should appear) 


  return(rsdAsylum)


}
plot_ctr_origin_recognition(year = 2022,
                     country_origin_iso3c = "VEN",
                     top_n_countries = 10, 
                     measure = "RefugeeRecognitionRate",
                     order_by = "TotalDecided" )
# test_that("plot_ctr_recognition works", {   expect_true(inherits(plot_ctr_recognition, "function")) })

4. Profile

Plot Age Pyramid

#' Population Pyramid
#'
#' @param year Numeric value of the year (for instance 2022). 
#'             If the data is not yet available for that year (aka still in the mid year reporting stage),
#'              it will automatically fall back on the previous year
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' @param pop_type Vector of character values. Possible population type (e.g.: REF, IDP, ASY, OIP, OOC, STA)
#' 
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  scale_color_manual scale_colour_manual 
#'             geom_text .pt theme_void
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  
#' @importFrom utils  head download.file
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace str_detect
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty
#' @importFrom stats  reorder aggregate  setNames
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join
#' @importFrom tidyr pivot_longer pivot_wider
#' @importFrom unhcrthemes theme_unhcr 
#' 
#' @return a ggplot2 object
#' 
#' @export
#'

plot_ctr_pyramid <- function(year ,
                             country_asylum_iso3c = country_asylum_iso3c,
                             pop_type = pop_type) {

  country_name_text <- ForcedDisplacementStat::reference |>
    filter(iso_3 == country_asylum_iso3c ) |>
    distinct(ctryname) |>
    pull()

  poptype_label <- ForcedDisplacementStat::end_year_population_totals_long |>
    filter(Population.type  %in% as.vector(pop_type)) |>
    distinct(population_type_label.short) |>
    pull()

  demographics1 <- ForcedDisplacementStat::demographics |>
    left_join( ForcedDisplacementStat::reference |>
                 select(UNHCRBureau, iso_3),  
               by = c("CountryAsylumCode" = "iso_3")) |>
    filter(CountryAsylumCode  == country_asylum_iso3c &
             year == year &
             Population.type  %in% as.vector(pop_type)) |>

    mutate ( totGen = FemaleTotal +MaleTotal,
             totbreak = Female04 + Female511 + Female1217 + 
               Female1859 + Female60ormore + FemaleUnknown +
               Male04 + Male511 + Male1217 + Male1859 +
               Male60ormore + MaleUnknown,

             hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

  ## Check if fall back is needed.. 
  if(nrow(demographics1) == 0) { 
    year <- year -1 
    demographics1 <- ForcedDisplacementStat::demographics |>
      left_join( ForcedDisplacementStat::reference |>
                   select(UNHCRBureau, iso_3),  
                 by = c("CountryAsylumCode" = "iso_3")) |>
      filter(CountryAsylumCode  == country_asylum_iso3c &
               year == year &
               Population.type  %in% as.vector(pop_type)) |>

      mutate ( totGen = FemaleTotal +MaleTotal,
               totbreak = Female04 + Female511 + Female1217 + 
                 Female1859 + Female60ormore + FemaleUnknown +
                 Male04 + Male511 + Male1217 + Male1859 +
                 Male60ormore + MaleUnknown,

               hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

    }




  if ( nrow(demographics1) ==  0 ){

    info <-  paste0("No Gender disaggregation recorded\n for Forcibly Displaced People across Borders \n in ", 
                    ctrylabel,
                    " as of ", 
                    year )

    p <- ggplot() +  annotate("text",  x = 1, y = 1, size = 12,  
                              label = info ) +  theme_void() 


  } else {

    tot <- format( sum(demographics1$Total) ,  big.mark=",")
    totprop <-   format( round( sum(demographics1$totGen) / 
                                  sum(demographics1$Total )  *100,1),  big.mark=",")  

    if (totprop == 0 ) {
      info <- paste0("There\'s no recorded Gender disaggregation \n for  all of the ",tot, " persons \n in ", country_name_text  )
      p <- ggplot() +  annotate("text",  x = 1, y = 1, size = 12,  
                                label = info ) +  theme_void() 


    } else {
      #names(demographics)
      pyramid <-  demographics1[ demographics1$year == max(demographics1$year),
                                 c(
                                   "Female04",
                                   "Female511",
                                   "Female1217",
                                   "Female1859",
                                   "Female60ormore",
                                   "FemaleUnknown",
                                   # "FemaleTotal",
                                   "Male04",
                                   "Male511",
                                   "Male1217",
                                   "Male1859",
                                   "Male60ormore",
                                   "MaleUnknown"#,
                                   # "MaleTotal"       
                                 )]  

      pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) |>
        pivot_longer(
          cols = Female04:MaleUnknown,
          names_to = "Class",
          values_to = "Sum",
          values_drop_na = TRUE
        ) 

      pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                          ),
                                          sum))
      names(pyramid3)[1] <- "Class"
      names(pyramid3)[2] <- "Count"

      pyramid3 <- pyramid3 |>
        mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                                  str_detect(Class, "Female") ~ "Female")) |>
        mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                               str_detect(Class, "511") ~ "5-11",
                               str_detect(Class, "1217") ~ "12-17",
                               str_detect(Class, "1859") ~ "18-59",
                               str_detect(Class, "60") ~ "60+",
                               str_detect(Class, "Unknown") ~ "Unknown")) 

      pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count)
      pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

      pyramid4 <- pyramid3 |>
        select(gender,age, pc) |>
        mutate(gender = tolower(gender)) |>
        pivot_wider(names_from = gender,
                    names_sort = TRUE,
                    values_from = pc
        ) 

      p <-  ggplot() +
        geom_col(data = pyramid4,
                 aes(-male, age,
                     fill = "Male"),  width = 0.7 ) +
        geom_col(data = pyramid4,
                 aes(female, age,
                     fill = "Female"),width = 0.7 ) +
        geom_text(data = pyramid4,
                  aes(-male, age,
                      label = percent(abs(male), accuracy = 1)),
                   hjust = 1.25,   size = 11.5 / ggplot2::.pt ) +
        geom_text(data = pyramid4,
                  aes(female,  age,                     
                      label = percent(abs(female), accuracy = 1)  ), 
                  hjust = -0.25,  size = 11.5 / ggplot2::.pt) +
        ## Now get the icon for male and female 
        # ggtext::geom_textbox(aes(x = 0.25, 
        #                           y = "60+",  
        #                 label = "\uf182" ), 
        #                family = "Font Awesome 6 Free Solid",
        #                color = "#18375F",# "#0072BC" "#8EBEFF"
        #                box.colour = NA ,   hjust = 0,   vjust = 0,
        #                width = unit(0.4, "npc"),
        #               size = 11.5 ) +
        # ggtext::geom_textbox(aes(x = as.numeric(-0.25), 
        #                          y = "60+",  
        #                label = "\uf183" ), 
        #               family = "Font Awesome 6 Free Solid",
        #                color = "#0072BC",# "#0072BC" "#8EBEFF"
        #               box.colour = NA ,   hjust = 0,   vjust = 0,
        #                width = unit(0.4, "npc"),
        #              size = 11.5 ) +
        scale_x_continuous(expand = expansion(c(0.2, 0.2))) +
        scale_fill_manual(breaks=c('Male', 'Female'),
                          values = setNames(
                            unhcr_pal(n = 3, "pal_unhcr")[c(2, 1)],
                            c("Male" , "Female")  )) +
        labs(  title = paste0("Population Pyramid for ", 
                              sub(",\\s+([^,]+)$", " and \\1",  toString(poptype_label)), 

                              " | ", ctrylabel),
          subtitle = paste0(" As of ", year, 

                            ", gender disaggregation is available for ", totprop, "% of the ",tot,
                            " individuals in ", country_name_text),
          caption = "Note: figures do not add up to 100 per cent due to rounding\nSource: UNHCR.org/refugee-statistics."  ) +
        theme_unhcr(font_size = 14, grid = FALSE, axis = FALSE, axis_title = FALSE,  axis_text = "y") +
        theme(legend.position = "none")
    }
  }

  return(p)
}
# 
plot_ctr_pyramid(year = 2022,
                 country_asylum_iso3c = "COL",
                 pop_type = c("ASY", "REF")
                 )

Plot locations within countries

#' Create a map with symbol proportional to population data by location within country
#'
#' @param year Numeric value of the year  (for instance 2022). 
#'             If the data is not yet available for that year (aka still in the mid year reporting stage),
#'              it will automatically fall back on the previous year
#'              
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' @param pop_type Vector of character values. Possible population type (e.g.: REF, IDP, ASY, OIP, OOC, STA)
#' @param  mapbackground can be "osm" (default), "stamen-toner" , "stamen-terrain","stamen-watercolor". 
#'            Other mapbackground requires an API key and were not considered 
#' 
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  geom_point
#'             scale_color_manual scale_colour_manual 
#'             scale_size_continuous element_rect
#'             geom_text .pt theme_void
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace str_detect  str_glue
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty
#' @importFrom stats  reorder aggregate  setNames
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join
#' @importFrom tidyr pivot_longer pivot_wider
#' @importFrom ggspatial geom_sf coord_sf
#' @importFrom sf st_as_sf st_set_crs st_bbox
#' @importFrom rnaturalearth ne_countries
#' @import rnaturalearthdata
#' @importFrom ggrepel geom_label_repel
#' @importFrom grDevices hcl.colors
#' @importFrom OpenStreetMap openmap openproj autoplot.OpenStreetMap
#' @importFrom unhcrthemes theme_unhcr
#' 
#' @return a ggplot2 object
#' 
#' @export
#'
plot_ctr_location <- function( year  ,
                             country_asylum_iso3c  ,
                             pop_type  ,
                             mapbackground = "osm" #  could be "stamen-toner" , "stamen-terrain","stamen-watercolor"
                             ) {

  country_name_text <- ForcedDisplacementStat::reference |>
    dplyr::filter(iso_3 == country_asylum_iso3c ) |>
    dplyr::distinct(ctryname) |>
    dplyr::pull()

  poptype_label <- ForcedDisplacementStat::end_year_population_totals_long |>
    dplyr::filter(Population.type  %in% as.vector(pop_type)) |>
    dplyr::distinct(population_type_label.short) |>
    dplyr::pull()

  # names(ForcedDisplacementStat::demographics)
  mapped1 <- ForcedDisplacementStat::demographics |>
    dplyr::filter(year == year,  #### Parameter
           CountryAsylumCode == country_asylum_iso3c, #### Parameter
           Population.type %in% pop_type  ) |>
    dplyr::group_by ( CountryAsylumCode, location) |>
    dplyr::summarise( Total = sum(Total, na.rm = TRUE)) |>
    dplyr::ungroup() |>
    ## add geometry
    dplyr::left_join( ForcedDisplacementStat::locpcode ,
               by = c("location" = "location"))

  ## Check if fall back is needed.. 
  if(nrow(mapped1) == 0) { 
    year <- year -1 
    mapped1 <- ForcedDisplacementStat::demographics |>
    dplyr::filter(year == year,  #### Parameter
           CountryAsylumCode == country_asylum_iso3c, #### Parameter
           Population.type %in% pop_type  ) |>
    dplyr::group_by ( CountryAsylumCode, location) |>
    dplyr::summarise( Total = sum(Total, na.rm = TRUE)) |>
    dplyr::ungroup() |>
    ## add geometry
    dplyr::left_join( ForcedDisplacementStat::locpcode ,
               by = c("location" = "location"))

    }


  nonmapped <- mapped1 |>
    dplyr::filter(   is.na( latitude) & is.na(longitude)) 
  mapped <- mapped1 |>
    dplyr::filter( ! is.na( latitude) | ! is.na(longitude))  |>
    dplyr::mutate (latitude =  as.double( latitude),
                   longitude =  as.double( longitude),
                   level = paste0( "Geographic precision level: ",location_level ),
                   location =factor(location, unique(location)) ) |>
    # Center: reorder your dataset first! Big cities appear later = on top
    dplyr::arrange(desc(Total) )

    pal <- grDevices::hcl.colors(3, "Inferno", rev = TRUE, alpha = 0.7)


    # Get Bounding box
    # plot(rnaturalearth::ne_countries(scale = "medium", returnclass = "sf")  |> dplyr::filter(iso_a3 == country_asylum_iso3c) |>dplyr::pull(geometry))
    # ctr <- rnaturalearth::ne_countries(scale = "medium", returnclass = "sf")
    requireNamespace("rnaturalearthdata")
    box <- sf::st_bbox(rnaturalearth::ne_countries(scale = "medium", returnclass = "sf")  |> 
                         dplyr::filter(iso_a3 == country_asylum_iso3c))
    LON1 <- as.numeric( box[1] - 0.1* (box[3]-box[1])) 
    LON2 <- as.numeric(box[3] + 0.1* (box[3]-box[1]))
    LAT1 <- as.numeric(box[2]  - 0.1* (box[4]-box[2]) )
    LAT2 <- as.numeric(box[4] + 0.1* (box[4]-box[2]) )

    # attempts to assign an object containing “longlat” to data extending beyond
    # longitude [-180, 180] or latitude [-90, 90] will be stopped.
    if(LON1 < -180){ LON1 <- -179}
    if(LON2 > 180){ LON2 <- 179}
    ## Need to trim a lot near the poles to get the webtiles
    if(LAT1 < -80){ LAT1 <- -70} 
    if(LAT2 > 80){ LAT2 <- 70}

    map <- OpenStreetMap::openmap(c(LAT2, LON1), c( LAT1, LON2), 
                                  zoom = NULL,
                                  type =  mapbackground, #"osm" , 
                                  #type =  "stamen-toner" , 
                                  # c("osm", "stamen-toner", "stamen-terrain","stamen-watercolor", "esri","esri-topo"),
                                  mergeTiles = TRUE)


    map.latlon <- OpenStreetMap::openproj(map, projection = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
    # Bubble choropleth map with SOM background
    p <- OpenStreetMap::autoplot.OpenStreetMap(map.latlon) +
         ggplot2::geom_point(  data = mapped ,
            pch = 21,  # , filled circle blue
            ggplot2::aes(x= longitude, y= latitude,
                size = Total,
                fill = level),
               col = "grey20",
              alpha=0.6   ) +
        ggplot2::scale_size_continuous(
          name="Population (in Th)",
          range = c(1, 9),
          breaks=  scales::breaks_pretty(5)) +
       ggplot2::scale_fill_manual(values = pal,
                    drop = FALSE,
                    na.value = "grey80") +
      ggrepel::geom_label_repel(   data = mapped |>head(5)  ,
                mapping = ggplot2::aes(x= longitude, y= latitude,
                          label = stringr::str_glue(  "{stringr::str_wrap(location,15)}\n{ scales::label_number(scale_cut = scales::cut_short_scale())(Total)} ")  # how label displays
                               ),
                          size = 2.5,   # text size in labels
                 min.segment.length = 0)+           # show all line segments  
        ggplot2::coord_sf(xlim = c(LON1 , LON2),   ylim = c(LAT1  ,LAT2 ), expand = FALSE) +
        ggplot2::labs(title = paste0( 

                                 format(round(sum(mapped1$Total), 0), scientific = FALSE, big.mark=","), " ",
                                # scales::label_number(scale_cut = scales::cut_short_scale())(sum(mapped1$Total)), 
                                 sub(",\\s+([^,]+)$", " and \\1",  toString(poptype_label)), 
                                " in ", country_name_text, " as of ", year),
             subtitle = paste0( "This is disaggregated through ",
                                 nrow(mapped),
                                 " locations at different geographic levels, \n representing a total of ",
                                 format(round(sum(mapped$Total), 0), scientific = FALSE, big.mark=","), 
                                # scales::label_number(scale_cut = scales::cut_short_scale())(sum(mapped$Total)), 
                                 " people.\n ",  format(round(nonmapped$Total, 0), scientific = FALSE, big.mark=","), 
                                 " are dispersed in the country (i.e ",
                                 round(nonmapped$Total/sum(mapped1$Total)*100, 1), "%)" ),
             caption = "The boundaries and names shown on this map do not imply \n official endorsement or acceptance by the United Nations",
             size = "Displaced Population") +
        unhcrthemes::theme_unhcr_map() +
        ggplot2::theme(legend.position = "none")
  return(p)
}
# plot_ctr_location(year = 2022,
#                  country_asylum_iso3c = "COL",
#                  pop_type = c("ASY", "REF", "OIP"))
# 
# plot_ctr_location(year = 2021,
#                  country_asylum_iso3c = "COL",
#                  pop_type = c("IDP"))
# 
# plot_ctr_location(year = 2022,
#                  country_asylum_iso3c = "CAN",
#                  pop_type = c("ASY", "REF", "OIP"))
# 
# plot_ctr_location(year = 2021,
#                  country_asylum_iso3c = "MEX",
#                  pop_type = c("ASY", "REF", "OIP"))
## test_that("plot_ctr_location works", {   expect_true(inherits(plot_ctr_location, "function")) 
# })

5. Processing

Plot Refugee Recognition rate in Country

#' Display a Chart with Refugee Recognition Rates 
#' 
#' In the absence of an internationally agreed methodology for calculating recognition rates,
#'  UNHCR uses two rates to compute the proportion of refugee claims accepted during the year: 
#'  
#'   * The Refugee Recognition Rate divides the number of asylum-seekers granted Convention refugee
#'   status by the total number of accepted (Convention and, where relevant, complementary 
#'   protection) and rejected cases (aka substantive decision). 
#'   
#'   * The Total Recognition Rate divides the number of asylum-seekers granted Convention
#'    refugee status and / or complementary form of protection by the total number
#'    of accepted (Convention and, where relevant, complementary protection) and
#'     rejected cases.
#'     
#' Non-substantive decisions are, to the extent possible, excluded from both 
#' calculations. For the purpose of international comparability,  UNHCR only 
#' uses these two recognition rates and does not report nationally calculated rates.
#'      
#'      See https://www.unhcr.org/4ce531e09.pdf
#' 
#' @param year Numeric value of the year  
#'              
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' @param top_n_countries Numeric value of number of main countries that the graph should display
#' @param measure this can be either:
#'            * RefugeeRecognitionRate 
#'            * TotalRecognitionRate
#' @param order_by this can be either:
#'            * Recognized  
#'            * ComplementaryProtection  
#'            * TotalDecided 
#'            
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  scale_color_manual scale_colour_manual 
#'             geom_text guide_axis facet_wrap vars
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace 
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty pretty_breaks
#' @importFrom stats  reorder aggregate 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join
#' @importFrom tidyr pivot_longer
#' @importFrom unhcrthemes theme_unhcr  scale_fill_unhcr_d
#' 
#' @return a ggplot2 object
#' 
#' @export
plot_ctr_recognition <- function(year = 2022,
                                 country_asylum_iso3c  ,
                                 top_n_countries = 10, 
                                 measure = "RefugeeRecognitionRate",
                                 order_by = "TotalDecided" ){

   country_name_text <- ForcedDisplacementStat::reference |>
                 filter(iso_3 == country_asylum_iso3c ) |>
               select(ctryname) |>
                pull()


   measurelabel <-
     dplyr::case_when(
       measure == "RefugeeRecognitionRate"  ~ "Refugee Recognition Rate",
       measure == "TotalRecognitionRate"  ~ "Total Recognition Rate"
     )

   order_bylabel <-
     dplyr::case_when(
       order_by == "Recognized"  ~ "Recognized Refugee Status Decisions",
       order_by == "ComplementaryProtection"  ~ "Complementary Protection Decisions",
       order_by == "TotalDecided"  ~ "Total Decision (independently of the outcome)"
     )

   topOrigin <-  ForcedDisplacementStat::asylum_decisions |>
     filter(CountryAsylumCode == country_asylum_iso3c &
              year == year) |>
     ## the below is change - DecisionsAveragePersonsPerCase- is just indicative... so no need to use it to m
     # mutate(DecisionsAveragePersonsPerCase = map_dbl(DecisionsAveragePersonsPerCase, ~replace_na(max(as.numeric(.), 1), 1))) |>
     mutate(DecisionsAveragePersonsPerCase = 1) |>
     group_by(CountryOriginName) |>
     summarize(
       Recognized = sum(Recognized * DecisionsAveragePersonsPerCase, na.rm = TRUE),
       ComplementaryProtection = sum(
         ComplementaryProtection * DecisionsAveragePersonsPerCase,
         na.rm = TRUE
       ),
       TotalDecided = sum(TotalDecided * DecisionsAveragePersonsPerCase, na.rm = TRUE)
     ) |>
     mutate(
       RefugeeRecognitionRate = (Recognized) / TotalDecided,
       TotalRecognitionRate = (Recognized + ComplementaryProtection) / TotalDecided
     ) |>
     # filter(TotalDecided  != 0) |>
     # filter(TotalDecided  > 1000)  |>
     mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", ""))

   topOrigin1 <-  topOrigin  |>
     mutate(measured = .data[[measure]])  |>
     mutate(order_by = .data[[order_by]])  |>
     arrange(desc(order_by)) |>
     head(top_n_countries)   




   rsdorigin <- ggplot() +
     geom_bar(data = topOrigin1, 
              aes(y = measured ,
                  x = reorder(CountryOriginName, measured)),
              stat = "identity", fill = "#0072bc") +
     coord_flip() +
     #scale_y_continuous( labels = scales::label_number(accuracy = 1,   scale_cut = cut_short_scale())) + ## Format axis number
     scale_y_continuous( labels =   scales::label_percent(accuracy = 0.1, suffix = "%")) +

     #facet_grid(.~ ctry_asy) +
     #  geom_hline(yintercept = 0, size = 1.1, colour = "#333333")   +
     labs(
       title = paste0(measurelabel, " | ", year, " in ", country_name_text),
       caption = 'Source: UNHCR.org/refugee-statistics ',
       subtitle = paste0(
         "For top ",
         top_n_countries,
         " Countries of Origin ordered by ",
         order_bylabel
       ),
       x = " ",  y = " " ) +
     theme_unhcr(
       grid = "Y",
       axis = "x",
       axis_title = "" ,
       font_size = 14
     ) +
     theme(#axis.text.x = element_blank(),
       # legend.position = "none",

       panel.grid.major.x = element_line(color = "#cbcbcb"),
       panel.grid.major.y = element_blank()) ### changing grid line that should appear) 


  return(rsdorigin)


}
plot_ctr_recognition(year = 2022,
                     country_asylum_iso3c = "USA",
                     top_n_countries = 10, 
                     measure = "RefugeeRecognitionRate",
                     order_by = "TotalDecided" )
# test_that("plot_ctr_recognition works", {   expect_true(inherits(plot_ctr_recognition, "function")) })

Asylum Applications & Decision over time

#' Asylum Applications & Decision over time
#' 
#' This charts allow to visualize trends in terms of asylum applications, decision and refugee status recognition
#' 
#' @param year Numeric value of the year (for instance 2020)
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' @param lag Number of year to used as comparison base
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  scale_color_manual scale_colour_manual 
#'             geom_text guide_axis facet_wrap vars
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace 
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty pretty_breaks
#' @importFrom stats  reorder aggregate 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join
#' @importFrom tidyr pivot_longer
#' @importFrom unhcrthemes theme_unhcr  scale_fill_unhcr_d
#' 
#' @return a ggplot2 object
#' 
#' @export

plot_ctr_asylum <- function(year = 2022,
                            country_asylum_iso3c = country_asylum_iso3, 
                            lag = 10){

     country_name_text <- ForcedDisplacementStat::reference |>
                 filter(iso_3 == country_asylum_iso3c ) |>
               select(ctryname) |>
                pull()

    apps <- ForcedDisplacementStat::asylum_applications|>
          filter(CountryAsylumCode == country_asylum_iso3c )|>
          group_by(year, CountryAsylumCode) |>
         summarize (NumberApplications = sum(NumberApplications , na.rm= TRUE) )

    decs <- ForcedDisplacementStat::asylum_decisions |>
          filter(CountryAsylumCode == country_asylum_iso3c ) |>
          group_by(year, CountryAsylumCode) |>
         summarize (Recognized = sum(Recognized , na.rm= TRUE),
                  ComplementaryProtection = sum( ComplementaryProtection , na.rm= TRUE),
                  OtherwiseClosed = sum(OtherwiseClosed , na.rm= TRUE),
                  Rejected = sum(Rejected , na.rm= TRUE),
                  TotalDecided = sum(TotalDecided , na.rm= TRUE))


 data <- dplyr::inner_join(apps, decs) |>  # names(data)
         dplyr::filter( year >= (year - lag)) |>
         dplyr::select( year,  NumberApplications, Recognized, TotalDecided ) |>
         tidyr::pivot_longer( 
              cols = NumberApplications:TotalDecided,
              names_to = "AsylumStage",
              values_to = "Total",
              values_drop_na = TRUE
            )
 # levels(as.factor(data$AsylumStage))
 data$AsylumStage <- dplyr::recode (data$AsylumStage, "NumberApplications"= "Total Number of Applications",
                                            "TotalDecided" = "Total Number of Decisions",
                                             "Recognized" = "Number of Refugee Status Recognition Decisions")
  data$AsylumStage <- factor(data$AsylumStage, levels = c("Total Number of Applications",
                                                          "Total Number of Decisions",
                                                          "Number of Refugee Status Recognition Decisions"))

 p <- ggplot() +
     geom_bar(data = data,
             aes(x= year, y = Total, fill = AsylumStage),
             stat = "identity", position = "dodge", width = 0.8 ) + 
     scale_fill_unhcr_d(palette = "pal_unhcr") +
    # scale_fill_manual(values = c( "#FAAB18", "#0072bc", "#FEEB18")) +  
     scale_x_continuous(breaks = pretty_breaks(10)) +
    # scale_x_discrete(guide = guide_axis(check.overlap = TRUE)) +
     scale_y_continuous( labels = scales::label_number(accuracy = 1, scale_cut = cut_short_scale()))+ ## Format axis number
     labs(title = paste0( " Asylum Applications & Decisions | ", country_name_text, " " ,  (year-lag) ," - ", year),
       subtitle = paste0( "Note that under certain circumstance, one person may have more than one applications "), 
       x="",
       y ="",
       caption = "Source: UNHCR.org/refugee-statistics") + 
     theme_unhcr(font_size = 14, ## Insert UNHCR Style
                 grid = "X" #, 
                #  axis = "Y", 
                #  axis_title = TRUE, 
                # axis_text = "Y" 
                )  +
     theme(panel.grid.major.y = element_line(color = "#cbcbcb"), 
           panel.grid.major.x = element_blank()) ### changing grid line that should appear

  return(p)




}
plot_ctr_asylum(year = 2022,
                country_asylum_iso3c = "ECU", 
                            lag = 10)
#test_that("plot_ctr_asylum works", {   expect_true(inherits(plot_ctr_asylum, "function")) })

Asylum Processing

#' Asylum Processing
#' 
#' Displaying Asylum processing 
#' 
#' @param year Numeric value of the year (for instance 2020)
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' @param otherprop value set by default to .02 - used to merge origin as "Other"
#' 
#' 
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  scale_color_manual scale_colour_manual 
#'             geom_text guide_axis facet_wrap vars theme_void
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace str_wrap
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty
#' @importFrom stats  reorder aggregate 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join rename count
#' @importFrom tidyr pivot_longer
#' @importFrom forcats fct_relevel
#' @importFrom  ggforce geom_parallel_sets geom_parallel_sets_axes  
#'                  geom_parallel_sets_labels gather_set_data
#' @importFrom unhcrthemes theme_unhcr
#' 
#' @return a ggplot2 object
#' 
#' @export 
plot_ctr_process <- function(year = 2022,
                             country_asylum_iso3c,
                             otherprop = .02){


  #table(as.factor(ForcedDisplacementStat::asylum_decisions_long$CountryAsylumCode))

  links <- ForcedDisplacementStat::asylum_decisions_long |>
    filter(year == year   & CountryAsylumCode  == country_asylum_iso3c ) |>
    dplyr::mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName,
                                                             prop = otherprop, 
                                                             w = value)) |>
    ## Group small records under other
    ## Calculate grouped value for Origin to procedure..
    group_by(CountryOriginName, ProcedureName, DecisionTypeName,Decision.output ) |>
    summarise(n = sum(value, na.rm = TRUE) )  
  # levels(links$Decision.output)

  ## Case no record outut a ggplot2 object with anotation
  if( nrow(links) == 0) {
    info <-  paste0("There\'s no recorded Asylum Decisions \n in ", ForcedDisplacementStat::reference |>
             dplyr::filter( iso_3 == country_asylum_iso3c) |>
             dplyr::pull(ctryname) , " for ", year)
    p <- ggplot() +  annotate(stringr::str_wrap("text", 80), 
                              x = 1, y = 1, size = 11,  
                              label = info ) +  theme_void() 

  } else {

  ## summarize data
 flow_table <- links  |>
  ggforce::gather_set_data(x = c("CountryOriginName","ProcedureName","DecisionTypeName","Decision.output") ) 


  flow_table$Decision.output <- factor(flow_table$Decision.output,
                                  levels = c("Rejected",
                                             "ComplementaryProtection",
                                             "Recognized",    
                                             "OtherwiseClosed"))
## plot your dataset 
  ## on the x axis is the start and end causes
  ## gather_set_data generates an ID for each possible combination
  ## splitting by y gives the possible start/end combos
  ## value as n gives it as counts (could also be changed to proportion)
p <- ggplot(flow_table, 
       aes(x, 
          id = id, 
          split = y, 
          value = n)) +
  ## colour lines by sex 
  ggforce::geom_parallel_sets( aes(fill = Decision.output),
                     alpha = 0.5,
                     axis.width = 0.2) +
  ## fill in the label boxes grey
  ggforce::geom_parallel_sets_axes(axis.width = 0.15,
                          fill = "grey80", 
                          color = "grey80") +
  ## change text colour and angle (needs to be adjusted)
  ggforce::geom_parallel_sets_labels(color = "black",
                            angle = 0,
                            size = 5) +
  ## adjusted y and x axes (probably needs more vertical space)
  scale_x_discrete(name = NULL, 
                   expand = c(0, 0.2)) + 
   theme_unhcr(font_size = 14, 
               grid = FALSE ) +
  ## remove axis labels
  theme(  axis.line = element_blank(),
          axis.ticks = element_blank(),
         axis.text.y = element_blank(),
        panel.background = element_blank(),
        legend.position = "none",                    # move legend to bottom
      legend.title = element_blank(),                # remove title
  ) +
  labs(title = "Refugee Status Determination Decisions",
       subtitle = glue::glue("{ForcedDisplacementStat::reference |>
             dplyr::filter( iso_3 == country_asylum_iso3c) |>
             dplyr::pull(ctryname) }, {format(sum(links$n),  big.mark=\",\")} decisions recorded in {year}"),
       x = NULL,
       y = NULL,
       caption = "Source: UNHCR.org/refugee-statistics")
}
  return(p)

}
plot_ctr_process(year = 2022,   country_asylum_iso3c = "BOL")

plot_ctr_process(year = 2022,   country_asylum_iso3c = "CHL")


plot_ctr_process(year = 2022,   country_asylum_iso3c = "USA",
                              otherprop = .02)

plot_ctr_process(year = 2022,   country_asylum_iso3c = "USA",
                              otherprop = .04)
# test_that("plot_ctr_process works", {   expect_true(inherits(plot_ctr_process, "function")) })

Average Asylum Processing Time

#' Plot Average processing time from registration to first instance asylum decision
#' 
#' This indicator measures the average number of days from the date of completion of registration of the asylum application to the date of notification of first instance asylum decision for all persons who were notified of a first instance RSD/asylum decision during the reporting period. 
#' 
#' Status determination procedures are a core protection function and the principle mechanism through which international protection needs of Persons of Concern may be determined in accordance with the key provisions of the 1951 Convention and 1967 Protocol relating to the Status of Refugees, the 1954 Convention relating to the Status of Stateless Persons, or relevant regional refugee protection instruments. Status determination procedures are therefore central to the full and effective enjoyment of the universal right to seek and enjoy asylum and the specific rights guaranteed by the above instruments.
#' 
#' A prolonged waiting period during the status determination procedure is an important indicator of the state of efficiency, fairness, adaptability integrity and hence, overall quality of the national asylum or, depending on the context, UNHCR Mandate RSD procedure, including the timeliness and effectiveness of the overall protection response in the country.
#'  
#'  (RBM Outcome Indicator 2.1) - see [UNHCR Intranet](https://intranet.unhcr.org/content/dam/unhcr/intranet/protection-operations/compass/en/guidance/3/coreindicatorsmetadata/2.0%20Core%20Indicator%20Metadata%2004%2010%202021.pdf#page=67) - Credit to Hisham Galal for the chart initial idea and script
#' 
#' @param year Numeric value of the year (for instance 2020)
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' 
#' @param country_origin_iso3c Character value with the ISO-3 character code of the Country of Asylum - if NUL then all countries are included
#' 
#' @param procedureType indicates whether "G" (Government) "J" (Joint) "U" (UNHCR)
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  scale_color_manual scale_colour_manual guides guide_legend
#'             geom_text guide_axis facet_wrap vars geom_area annotate
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  scale_fill_manual
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace 
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty
#' @importFrom tidyr pivot_longer 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join last transmute
#' @importFrom purrr detect_index
#' @importFrom lubridate date_decimal interval days make_date
#' @importFrom unhcrthemes theme_unhcr
#' 
#' @return a ggplot2 object
#' 
#' @export
plot_ctr_processing_time <- function(year = 2022,
                              country_asylum_iso3c = country_asylum_iso3,
                              country_origin_iso3c = NULL,
                              procedureType = NULL){


#   library(tidyverse)
# library(lubridate)
# library(jsonlite)
#   country_asylum_iso3c <- "CHL" # iso3 code

  if( is.null(country_origin_iso3c)) {
        originfilter <-     c(ForcedDisplacementStat::asylum_applications |>
                                      dplyr::select(CountryOriginCode) |>
                                      unique() |>
                                    dplyr::pull() ) 
        originfilterlab <- ""
        } else { 
        originfilter <- c(country_origin_iso3c) 
        originfilterlab <- ForcedDisplacementStat::reference |>
                                   dplyr::filter( iso_3 == country_origin_iso3c) |>
                                   dplyr::pull(ctryname)}
  if( is.null(procedureType)) {
          procedurefilter <-     c(ForcedDisplacementStat::asylum_applications |>
                                      dplyr::select(ProcedureType) |>
                                      unique() |>
                                    dplyr::pull() )
          procedurefilterlab <- ""
          } else { 
          procedurefilter <- c(procedureType)
          procedurefilterlab <- ForcedDisplacementStat::asylum_applications |>
                                      dplyr::filter(ProcedureType == procedureType ) |>
                                     dplyr::select(ProcedureName)|>
                                      unique() |>
                                    dplyr::pull()}
   filterlab <- paste0( dplyr::if_else( originfilterlab == "",
                                        "",
                                        paste0( ", filtered for nationals from ",
                                                originfilterlab)),
                        dplyr::if_else( originfilterlab == "",
                                        "",
                                        paste0( " processed by ", 
                                                procedurefilterlab, " ")))




    apps <- ForcedDisplacementStat::asylum_applications |>
          filter(CountryAsylumCode == country_asylum_iso3c )|>

          ## add conditional filter  if setup
          filter(CountryOriginCode %in% c(originfilter)  ) |>
          filter(ProcedureType %in% c(procedurefilter)  ) |>


          mutate ( DecisionTypeCode  = dplyr::case_when (
            (ApplicationTypeCode %in% c("N", "NR", "NA", "FA", "SP") ) ~ "FI",
             # | 
             #  (ApplicationTypeCode == "V" & 
             #    DecisionType %in% c("FI", "FA", "NA", "TR", "CA")) ) ~ "FI",
            TRUE ~ "Other"   )) |>
          group_by(year, CountryAsylumCode,
                   CountryAsylumName, 
                   #ProcedureType,  ProcedureName,  ApplicationTypeCode, ApplicationType
                   DecisionTypeCode ) |>
         summarize (NumberApplications = sum(NumberApplications , na.rm= TRUE) )  |>
          dplyr::ungroup()
#     
#   # coa <-   "CHL"
#     
#   ## Equivalent to this API - call 
# # apps1 <- jsonlite::fromJSON(glue::glue("https://api.unhcr.org/population/v1/asylum-applications/?limit=100&dataset=asylum-applications&displayType=totals&yearFrom=1951&yearTo=2022&coa={coa}&columns%5B%5D=procedure_type&columns%5B%5D=app_type&columns%5B%5D=app_pc&columns%5B%5D=app_size&columns%5B%5D=dec_level&columns%5B%5D=applied"))$items |> as_tibble()

  if( is.null(country_origin_iso3c)) {
        originfilter <-     c(ForcedDisplacementStat::asylum_decisions |>
                                      dplyr::select(CountryOriginCode) |>
                                      unique() |>
                                    dplyr::pull() ) } else { 
        originfilter <- c(country_origin_iso3c) }
  if( is.null(procedureType)) {
          procedurefilter <-     c(ForcedDisplacementStat::asylum_decisions |>
                                      dplyr::select(ProcedureType) |>
                                      unique() |>
                                    dplyr::pull() ) } else { 
          procedurefilter <- c(procedureType) }
# 
  decs <- ForcedDisplacementStat::asylum_decisions |>
          filter(CountryAsylumCode == country_asylum_iso3c ) |>
          ## add conditional filter  if setup
          filter(CountryOriginCode %in% c(originfilter)  ) |>
          filter(ProcedureType %in% c(procedurefilter)  ) |>

          group_by(year, CountryAsylumCode,
                   CountryAsylumName, 
                   #ProcedureType,  ProcedureName,, DecisionTypeName
                   DecisionTypeCode) |>
         summarize (Recognized = sum(Recognized , na.rm= TRUE),
                  ComplementaryProtection = sum( ComplementaryProtection , na.rm= TRUE),
                  OtherwiseClosed = sum(OtherwiseClosed , na.rm= TRUE),
                  Rejected = sum(Rejected , na.rm= TRUE),
                  TotalDecided = sum(TotalDecided , na.rm= TRUE)) |>
          dplyr::ungroup()

  ## Equivalent to this API - call 
 # decs1 <- jsonlite::fromJSON(glue::glue("https://api.unhcr.org/population/v1/asylum-decisions/?limit=100&dataset=asylum-decisions&displayType=totals&yearFrom=1951&yearTo=2022&coa={coa}&columns%5B%5D=procedure_type&columns%5B%5D=dec_level&columns%5B%5D=dec_pc&columns%5B%5D=dec_recognized&columns%5B%5D=dec_other&columns%5B%5D=dec_rejected&columns%5B%5D=dec_closed&columns%5B%5D=dec_total"))$items |>as_tibble() 

data <-
  left_join(apps |>filter(DecisionTypeCode  == "FI") |>select(year, CountryAsylumCode, NumberApplications),
            decs |>filter(DecisionTypeCode == "FI") |>select(year, CountryAsylumCode, TotalDecided) ) |>
  arrange(year) |>
  mutate(across(c(NumberApplications,
                  TotalDecided),
                replace_na, 0)) |>
  dplyr::transmute(year = if_else(year == last(year),
                           year+.5,
                           year+1), # MYSR correction
            apps = cumsum(NumberApplications),
            decs = cumsum(TotalDecided))  

  idx <- purrr::detect_index(data$apps, ~.< dplyr::last(data$decs),
                                           .dir = "backward")

  t <- lubridate::date_decimal(data$year[idx] + 
                                 (dplyr::last(data$decs) - data$apps[idx]) / 
                                 (data$apps[idx+1] - data$apps[idx]))

  stat <- lubridate::interval(t, lubridate::make_date(2022, 6, 30)) / lubridate::days()

  data2 <- data |>
      tidyr::pivot_longer(- year, 
                          names_to = "flow",
                          values_to = "n")



  p <- data2 |>
    ggplot(aes(year,
               n, 
               fill = flow)) +
    geom_area(position = "identity") +
    ## highlight the main indicator!
    annotate("segment",
             x = lubridate::decimal_date(t),
             y = dplyr::last(data$decs),
             xend = dplyr::last(data$year),
             yend = dplyr::last(data$decs)) +
    annotate("text",
             x = 2020,
             y = last(data$decs),
             vjust = -.5,
             label = glue::glue("{round(stat)} days")) +
    scale_y_continuous(labels = scales::label_comma()) +
    scale_fill_manual(labels = c(decs = "Decisions",
                                 apps = "Applications"),
                      values = c(decs = "#0072BC",
                                 apps = "#FAEB00"),
                      name = NULL) +
    labs(title = stringr::str_wrap("Average Processing Time from Asylum Registration to First Instance Decision", 100),
         subtitle = glue::glue("In {ForcedDisplacementStat::reference |>
                                   dplyr::filter( iso_3 == country_asylum_iso3c) |>
                                   dplyr::pull(ctryname)}, comparative cumulative applications and decisions with gap measured in days as of {year} {filterlab}"),
         x = NULL,
         y = "Cumulative total",
         caption = "Source: UNHCR.org/refugee-statistics") +
    guides(fill = guide_legend(reverse = TRUE)) +
    theme_unhcr(font_size = 14, 
                grid = "Y")  + ## Insert UNHCR Style
    theme(legend.position = "top")

  return(p)

}
plot_ctr_processing_time(year = 2022,
                         country_asylum_iso3c = "ARG")


plot_ctr_processing_time(year = 2022,
                         country_asylum_iso3c = "USA")

## Display a filtered version of the chart for a specific country and procedure
plot_ctr_processing_time(year = 2022,
                         country_asylum_iso3c = "EGY",
                         country_origin_iso3c = "ERI",
                         procedureType = "U")
#test_that("plot_ctr_processing_time works", { expect_true(inherits(plot_ctr_processing_time, "function")) })

6. Solutions

Plot Solution Over time

#' Plotting solutions within a country
#' 
#' As part of UNHCR standard approach, there are mostly 3 types of durable solutions for Refugees:
#'  - Voluntary Repatriation in origin country 
#'  - Naturalization in the host country
#'  - Resettlement in a third country 
#'
#' @param year Numeric value of the year (for instance 2020)
#' @param lag Number of year to used as comparison base
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' @param sol_type Vector of character values. Possible population type (e.g.:"NAT" "RST" "RET" "RDP")
#' 
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  scale_color_manual scale_colour_manual 
#'             geom_text guide_axis facet_wrap vars
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace 
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty
#' @importFrom stats  reorder aggregate 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join
#' @importFrom tidyr pivot_longer
#' @importFrom unhcrthemes theme_unhcr
#' 
#' @return a ggplot2 object
#' 
#' @export
#'

plot_ctr_solution <- function(year = 2021,
                              lag = 10,
                              country_asylum_iso3c = country_asylum_iso3c,
                              sol_type ){

    country_name_text <- ForcedDisplacementStat::reference |>
                 filter(iso_3 == country_asylum_iso3c ) |>
               select(ctryname) |>
                pull()


    Solution <- ForcedDisplacementStat::solutions_long  |>
                dplyr::left_join(y= ForcedDisplacementStat::reference, 
                               by = c("CountryAsylumCode" = "iso_3")) |>

              filter(CountryAsylumCode  == country_asylum_iso3c & 

                      Year > (year - lag) &
                      Solution.type  %in% sol_type 
                      #Solution.type.label != "IDP returns" 
                      ) |>
              mutate(Year = as.factor(Year) ) |>
              group_by(Year, Solution.type.label ) |>
              summarise(Value2 = sum(Value) )  |>

              mutate( valabel =  ifelse(Value2 > 1000, 
                                       paste(scales::label_number(accuracy = 0.1,
                                                      scale_cut = cut_short_scale())(Value2)),
                                       as.character(Value2)) )   



    ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
    #levels(as.factor(solutions_long.asy$Solution.type.label))
    Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                     levels = c("Naturalisation", 
                                                                "Resettlement arrivals",
                                                                "Refugee returns",
                                                                "IDP returns" )) 



if( nrow(Solution) ==  0 ){

    info <-  paste0("There\'s no recorded solutions \n in ", ForcedDisplacementStat::reference |>
             dplyr::filter( iso_3 == country_asylum_iso3c) |>
             dplyr::pull(ctryname) , " for ", year)
    p <- ggplot() +  annotate(stringr::str_wrap("text", 80), 
                              x = 1, y = 1, size = 11,  
                              label = info ) +  theme_void()  

} else {


#Make plot
p <- ggplot(Solution, aes(x = year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
 # scale_y_continuous( labels = scales::label_number(accuracy = 1,   scale_cut = cut_short_scale())) + ## Format axis number

  scale_y_continuous( labels = scales::label_number(accuracy = 1,   scale_cut = cut_short_scale()))+

  scale_x_discrete(guide = guide_axis(check.overlap = TRUE))+
  #xlim(c(year-lag, year +1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  #geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  theme_unhcr(font_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "What are the trends in terms of Solutions?",
       subtitle = paste0("Data for Forcibly Displaced People across Borders as of ", year, " filtered for ", country_name_text ), 
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics.\n Resettlement – in this context this is the country of arrival – i.e. the country to which a refugee has been resettled \n Returns – in this context this is the country of departure – i.e. the country from which a refugee has voluntarily repatriated.")

}

return(p)
}
plot_ctr_solution(year = 2021,
                  country_asylum_iso3c= "UGA",
                  lag = 10,
                  sol_type = c("NAT", "RST", "RET", "RDP"))
#test_that("plot_ctr_solution works", {expect_true(inherits(plot_ctr_solution, "function")) })

Plot Solution Over Recognition

#' Title
#' 
#' Description

#' @param year Numeric value of the year (for instance 2020)
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' @param lag Number of year to used as comparison base
#' 
#' @import ForcedDisplacementStat 
#' @importFrom unhcrthemes theme_unhcr
#' @importFrom ggtext element_markdown
#' @importFrom dplyr  desc select  filter mutate group_by filter summarise ungroup
#'               pull   full_join
#' @importFrom tidyr pivot_longer  pivot_wider  
#' @importFrom ggbraid geom_braid 
#' @importFrom lubridate ymd  
#' @importFrom stringr str_wrap   
#' @importFrom scales label_number cut_short_scale    
#' 
#' @return a ggplot2 object
#' @export
plot_ctr_solution_recognition <- function(year = 2021,
                              lag = 10,
                              country_asylum_iso3c = country_asylum_iso3c){
   ctrylabel <- ForcedDisplacementStat::reference |> 
                 filter(iso_3 == country_asylum_iso3c ) |> 
               select(ctryname) |> 
                pull()


  new_refugee_recognitions_and_refugee_like_increases <-
    ForcedDisplacementStat::asylum_decisions |>
    filter(CountryAsylumCode == country_asylum_iso3c  &
             Year > (year - lag))  |>
    mutate(Year = as.factor(Year)) |>
    group_by(Year, CountryAsylumCode) |>
    summarize (new_refugee_recognitions_and_refugee_like_increases = sum(Recognized , na.rm = TRUE))

  refugee_solutions_naturalisation_resettlement_and_returns  <-
    ForcedDisplacementStat::solutions_long  |>
    filter(
      CountryAsylumCode  == country_asylum_iso3c &
        Year > (year - lag) &
        Solution.type.label != "IDP returns"
    ) |>
    mutate(Year = as.factor(Year)) |>
    group_by(Year, CountryAsylumCode) |>
    summarise(refugee_solutions_naturalisation_resettlement_and_returns = sum(Value))

  df_raw <-
    full_join(
      refugee_solutions_naturalisation_resettlement_and_returns,
      new_refugee_recognitions_and_refugee_like_increases,
      by = c("Year", "CountryAsylumCode")
    )|>
      dplyr::mutate(Year = lubridate::ymd(Year, truncated = 2L)) 


  if( nrow(df_raw) ==  0 ){

    info <-  paste0("There\'s no recorded solutions or recognitions \n in ", ForcedDisplacementStat::reference |>
             dplyr::filter( iso_3 == country_asylum_iso3c) |>
             dplyr::pull(ctryname) , " for ", year)
    p <- ggplot() +  annotate(stringr::str_wrap("text", 80), 
                              x = 1, y = 1, size = 11,  
                              label = info ) +  theme_void()  

  } else {

    df_long <- df_raw |>
      dplyr::rename(new = new_refugee_recognitions_and_refugee_like_increases,
                    sol = refugee_solutions_naturalisation_resettlement_and_returns) |>
      dplyr::mutate(year = lubridate::ymd(Year, truncated = 2L)) |>
      tidyr::pivot_longer(cols = new:sol)

    df_wide <-
      tidyr::pivot_wider(df_long, 
                         names_from = name, 
                         values_from = value)

    p <-
    ggplot() +
    ggbraid::geom_braid(data = df_wide,
                        aes( x = year,
                          ymin = new,
                          ymax = sol,
                          fill = new < sol
                        ),
                        alpha = 0.3) +
    geom_line(data = df_long,
              aes(x = year, y = value, color = name),
              linewidth = .75) +
    scale_x_date() +
    scale_y_continuous(
      labels = scales::label_number(scale_cut = scales::cut_short_scale()),
      limits = c(0, NA),
      expand = expansion(c(0, 0.02))
    ) +
    scale_color_manual(values = c("#0072bc", "#00B398")) +
    scale_fill_manual(values = c("#0072bc", "#00B398")) +
    labs(title = stringr::str_wrap( "How do <span style='color:#0072bc;'>refugee recognitions<sup>a</sup></span> compare with available <span style='color:#00B398;'>solutions<sup>b</sup></span>?", 80),
         subtitle = paste0("Data  for ", ctrylabel , " as of ", year ), 
         caption = "Source: UNHCR.org/refugee-statistics \n (a) Refugee recognition refers to the legal process through which an individual is granted refugee status by a country's government.\n (b) Refugee solutions includes returns, i.e departure to country of origin, resettlement to a third country and naturalization.") +
    unhcrthemes::theme_unhcr(
      font_size = 14,
      legend = FALSE,
      axis_title = FALSE,
      grid = "Yy"
    ) +
    theme(
      ## used to display part of the title in different colors
      plot.title = ggtext::element_markdown()
    )

  }

  return(p)

}
plot_ctr_solution_recognition(year = 2022,
                  country_asylum_iso3c= "UGA",
                  lag = 10)
#test_that("plot_ctr_solution_recognition works", {   expect_true(inherits(plot_ctr_solution_recognition, "function")) })

7.Migrant

plot share displaced / migrant for world - region - subregion

bar with share

Plot share displaced / migrant for top countries

dumbel

Plot Ratio Refugee Migrant

#' Plotting ratio Refugee/Asylum-seekers vs Migrant within a country
#' 
#' This chart provides insights on the relative weight of Forced Displacement for countries generating such type of displacement.
#' First, the size of the circle represents the number of Refugees, Asylum-seekers and other in need of International Protection
#' The vertical axis represent the Share of immigrants from the country in relation with all immigrants within the country. 
#' The higher is country in this axis, the more people from this country are the host country independently of the reason why they migrated.   
#' The horizontal axis displays the share of migration generated by forced displacement within each country of origin. 
#' The more a country is right, the more people from that country cam because of Forced Displacement.
#'  
#'
#' @param year Numeric value of the year (for instance 2020)
#' @param country_asylum_iso3c Character value with the ISO-3 character code of the Country of Asylum
#' @param top_n_countries Numeric value of number of main countries that the graph should display
#' 
#' @importFrom ggplot2  ggplot  aes  coord_flip   element_blank element_line
#'             element_text expansion geom_bar geom_col geom_hline unit stat_summary
#'             geom_label geom_text labs  position_stack  scale_color_manual scale_colour_manual 
#'             geom_text geom_point scale_size coord_cartesian theme_void
#'             scale_fill_manual scale_x_continuous scale_x_discrete  scale_y_continuous   sym theme  
#' @importFrom utils  head
#' @importFrom tidyselect where
#' @importFrom stringr  str_replace 
#' @importFrom scales cut_short_scale label_percent label_number breaks_pretty
#' @importFrom stats  reorder aggregate 
#' @importFrom dplyr  desc select  case_when lag mutate group_by filter summarise ungroup
#'               pull distinct n arrange across slice left_join across 
#' @importFrom tidyr pivot_longer
#' @importFrom unhcrthemes theme_unhcr
#' @importFrom viridis scale_fill_viridis
#' @import ForcedDisplacementStat 
#' 
#' @return a ggplot2 object
#' 
#' @export
#'
plot_ctr_disp_migrant <- function(year = 2021,
                              country_asylum_iso3c ,
                              top_n_countries = 10){

  country_name_text <- ForcedDisplacementStat::reference |>
                 filter(iso_3 == country_asylum_iso3c ) |>
               select(ctryname) |>
                pull()

  thiscodeM49 <- ForcedDisplacementStat::reference |>
                filter(iso_3 == country_asylum_iso3c) |>
                 select(M49_code) |>
                 pull()

  wb_data <- ForcedDisplacementStat::wb_data |>
              filter( iso_3 == country_asylum_iso3c)
  ## World bank API to retrieve total population
  # wb_data <- wbstats::wb( indicator = c("SP.POP.TOTL", "NY.GDP.MKTP.CD", "NY.GDP.PCAP.CD", "NY.GNP.PCAP.CD"),
  #            
  #              country = c( country_asylum_iso3c )  ,         
  #              startdate = 1990, 
  #              enddate = year, 
  #              return_wide = TRUE)
  # 
  # # Renaming variables for further matching
  # names(wb_data)[1] <- "iso_3"
  # names(wb_data)[2] <- "year"



  #   WDI::WDI(country = c(country_asylum_iso3c ) ,
  #                     indicator=c("SP.POP.TOTL", "NY.GDP.MKTP.CD", "NY.GDP.PCAP.CD", "NY.GNP.PCAP.CD"),
  #                     start = 1990, 
  #                     end = year,
  #                     extra = TRUE)   
  # # Renaming variables for further matching
  # names(wb_data)[3] <- "iso_3"
  # names(wb_data)[4] <- "year"
  # wb_data$year <- as.numeric(wb_data$year)

  ## Getting summary of forcibly displaced   ##############
  displaced <- left_join( x= ForcedDisplacementStat::end_year_population_totals_long, 
                               y= ForcedDisplacementStat::reference, 
                               by = c("CountryAsylumCode" = "iso_3")) |>
              filter(Population.type  %in% c("REF", "ASY", "OIP")) |>
              filter(CountryAsylumCode == country_asylum_iso3c) |>
              filter( year == max(year) ) |>
              mutate( iso_3 = CountryOriginCode) |>
              group_by(year, iso_3,CountryOriginName, UNHCRBureau, hcr_subregion, INCOME_GRP) |>
              summarise(Asylum_Refugee_in = sum(value, na.rm = TRUE) )  |>
              filter( iso_3 != "UKN") |>
              arrange( desc(Asylum_Refugee_in)) |>
             # head(10)|>
              as.data.frame()


  ## Now getting migrant data  ##############
  migrant <-  left_join( x= ForcedDisplacementStat::migrants, 
                               y= ForcedDisplacementStat::reference, 
                               by = c("CountryOriginM49" = "M49_code")) |>
              filter(CountryDestinationM49 == thiscodeM49) |>
              filter( year == 2020 ) |>
              as.data.frame() |>
              group_by(year, iso_3,CountryOriginName, UNHCRBureau, hcr_subregion, INCOME_GRP) |>
              summarise(Immigrant = sum(value) ) |>
              ungroup()#|>
              #mutate( shareOrgin = (Immigrant / sum(Immigrant, na.rm = TRUE))*100 ) |>
              #mutate( year = as.numeric(year) ) |>
              #mutate(  )


  ## Now merge everyting   #########
  thismigProfile <-  migrant  |>
    dplyr::full_join( displaced |>select(Asylum_Refugee_in, iso_3), by = c("iso_3")) |>
    dplyr::mutate(  SP.POP.TOTL = as.integer(wb_data |>filter( year == 2020) |>pull(SP.POP.TOTL) ) ) |>
     #mutate_each(funs(replace(., which(is.na(.)), 0))) |>
        mutate(across( where(is.numeric), ~replace_na(.,0)))|>
    ## Calculate a few ration
    mutate(  totImmigrant =   Immigrant + Asylum_Refugee_in  ,
   # mutate(  totImmigrant =   rowSums(as.integer(Immigrant) , as.integer(Asylum_Refugee_in), na.rm = TRUE )  )
   #    ,
             ratioAsylum_Immigrant = round(Asylum_Refugee_in / totImmigrant, 4),
             shareOrgin =  round(totImmigrant / sum(totImmigrant, na.rm = TRUE),4),

             ratioAsylum_Refugee_in = Asylum_Refugee_in / SP.POP.TOTL,
            ratioImmigrant = Immigrant / SP.POP.TOTL )  |>
    arrange( desc(Asylum_Refugee_in)) |>
   head(top_n_countries)


if( nrow(displaced) ==  0 ){

     info  <- paste0("No records of \n Forcibly Displaced People across Borders \n in ",ctrylabel )

     p <- ggplot() +  annotate("text",  x = 1, y = 1, size = 12,  
                                        label = info ) +  theme_void() 

} else {

p <- ggplot(thismigProfile,
       aes(x= ratioAsylum_Immigrant, 
           y= shareOrgin, 
           size= Asylum_Refugee_in/100, 
           #fill= INCOME_GRP,
           label = iso_3)) +
  geom_point(alpha=0.5, 
             shape=21, 
             color="black",
             fill = "#0072BC") +
  scale_size(range = c(.1, 20), guide= "none", ## Do not show Legend
             name="# of Forcibly Displaced People") +
  #viridis::scale_fill_viridis(discrete=TRUE,  name="Country Income Classification") +
  scale_x_continuous(labels = scales::label_percent(accuracy = .1),
                     expand = expansion(mult = c(0.1, .2))) +
  scale_y_continuous(labels = scales::label_percent(accuracy = .1),
                     expand = expansion(mult = c(0.1, .2))) +
  # facet_wrap( vars(year ), ncol = 2) +
  #coord_cartesian(clip = "off") +
  ggrepel::geom_label_repel(box.padding = 0.5,
                            size = 3,
                            # max.overlaps = 2 
                            fill = "white", 
                            xlim = c(-Inf, Inf), 
                            ylim = c(-Inf, Inf)) + 
  labs(title = stringr::str_wrap( paste0("Share of Forcibly Displaced People within all Migrants in ", country_name_text  ),90) ,
       subtitle = stringr::str_wrap("This chart provides insights on the relative weight of Forced Displacement for countries generating such type of displacement.
       First, the size of the circle represents the number of Refugees, Asylum-seekers and other in need of International Protection for the main origin of displacement.
       The vertical axis represent the Share of immigrants from each country in relation with all immigrants within the country. 
       The horizontal axis displays the share of migration generated by forced displacement.", 120), 
       y = "Share among all migrants",  #shareOrgin, 
       x ="Ratio Displaced / Immigrant",  # ratioAsylum_Immigrant, 
       caption = stringr::str_wrap("Source: UNHCR.org/refugee-statistics (includes REF +ASY+OIP in calculation) & UNDESA Migrant Stock as of 2020.\n Only main top 10 countries (or less depending on data availibility) linked to Forced Displaced across Borders are presented. Be cautious in the interpretation: data on Migrants are produced every 5 years and may have some gaps.", 120) ) +
  theme_unhcr( font_size = 12 ,
               rel_small = 6/9,
               rel_tiny = 5/9,
               rel_large = 12/7)  + ## Insert UNHCR Style
  theme(legend.position="none", 
       # plot.subtitle = element_text(size = 12),
        panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_line(color = "#cbcbcb"), 
        panel.grid.minor = element_blank())   ### changing grid line that should appear

}
#    The higher is country in this axis, the more people from this country are the host country independently of the reason why they migrated. \n\n  
      #    The more a country is right, the more people from that country cam because of Forced Displacement.
return(p)

}
plot_ctr_disp_migrant(year = 2022,
                    country_asylum_iso3c = "MEX" ,
                    top_n_countries = 10)
# plot_ctr_disp_migrant(year = 2022,
#                     country_asylum_iso3c = "FRA" )
#test_that("plot_ctr_disp_migrant works", {   expect_true(inherits(plot_ctr_disp_migrant, "function")) })

Refresh package

# Keep eval=FALSE to avoid infinite loop in case you hit the knit button
# Execute in the console directly
fusen::inflate(flat_file = "dev/dev_plot_Country.Rmd", vignette_name = "Chart Library Country", overwrite = 'yes')
pkgdown::build_site()


Edouard-Legoupil/unhcrdatapackage documentation built on Nov. 6, 2023, 6:10 p.m.