---
title: "Loan bridge timing"
description: >
  Tier 5 (timing). Bridge segment-length and timing figures from the gateway
  roster and `tstm_loans_bridges_type` (issue #34).
vignette: >
  %\VignetteIndexEntry{Loan bridge timing}
  %\VignetteEngine{quarto::html}
  %\VignetteEncoding{UTF-8}
knitr:
  opts_chunk:
    collapse: true
    comment: "#>"
---

This vignette implements Part 3 of [I-34](https://github.com/FanWangEcon/PrjThaiHFID/issues/34).

**Unit of observation:** the loan bridge (a sequence of linked loans behind one household investment), decomposed into five common-start time segments for visualization; timing analysis uses asset definition `agg_BS_1011`.

## Outputs at a glance

This vignette is **visualization-focused**: it renders figures and does **not** save a packaged dataset. Figures are written under `res/res_bridge_timing/` when the corresponding `ls_save_res` flag is set to `TRUE` (all default `FALSE`); on-page display is controlled separately by `bl_img_print_on_page`.

- **Inputs:** packaged [`tstm_roster_invest2loan2bridge`](../reference/tstm_roster_invest2loan2bridge.html) and [`tstm_loans_bridges_type`](../reference/tstm_loans_bridges_type.html) (both produced by [`ffv_invest_loan_bridge.qmd`](ffv_invest_loan_bridge.qmd)).
- **Figures:** bridge-timing visualizations showing formal/informal loan segments along a common-start timeline, grouped by bridge linkage type.

Load libraries, etc.

```{r setup}
library(PrjThaiHFID)
library(dplyr)
library(tidyr)
library(ggplot2)
library(readr)

# controls
verbose <- TRUE
it_row_print <- 50
it_file_code <- 308063
bl_img_print_on_page <- TRUE

# storage path
# here::here() resolves to vignettes/ under Quarto (temporary _quarto.yml);
# find the package root explicitly so paths resolve under Quarto and knitr.
spn_pkg_root <- rprojroot::find_root(rprojroot::has_file("DESCRIPTION"))
spn_res <- file.path(
  spn_pkg_root,
  "res", "res_bridge_timing",
  fsep = .Platform$file.sep
)
spt_res <- spn_res

# per-figure save flags (keys match the ls_plot element names); all default FALSE
ls_save_res <- list(
  `agg_BS_1011_st_bridge_forinf_d1m5_all_groups` = FALSE,
  `agg_BS_1011_st_bridge_forinf_d1m5_i-i-i` = FALSE,
  `agg_BS_1011_st_bridge_forinf_d1m5_f-i-f` = FALSE,
  `agg_BS_1011_st_bridge_forinf_d1m5_f-f-f` = FALSE,
  `agg_BS_1011_st_bridge_forinf_d1m5_f-mid` = FALSE,
  `agg_BS_1011_st_bridge_forinf_d1m5_i-mid-i2` = FALSE
)
```

## Packaged data inputs

This vignette **does not** call the investment–loan–bridge gateway. It reads two objects
from the package `data/` folder (lazy-loaded via `library(PrjThaiHFID)`):

| Object | Role |
|--------|------|
| `tstm_roster_invest2loan2bridge` | Distinct-bridge invest–loan roster (Group D) |
| `tstm_loans_bridges_type` | Triply linked loan bridges (Group A) |

**Provenance.** Both are among the eight `.rda` files written by
[`vignettes/ffv_invest_loan_bridge.qmd`](ffv_invest_loan_bridge.qmd) (issue
[#32](https://github.com/FanWangEcon/PrjThaiHFID/issues/32)), which runs
`ffp_hfid_invest_loan_linked_abc_investloan_char_gateway()`. With
`bl_replace_data_output <- TRUE` in that vignette, outputs overwrite canonical
`data/`. See `?tstm_roster_invest2loan2bridge` and `R/data-res.R` for variable
definitions (MBF filters, three paper asset ivars, anonymized household IDs).

**Refresh inputs and use them here**

1. Edit gateway parameters in `ffv_invest_loan_bridge.qmd` if needed (`ar_st_vars_to_keep`,
   month/size cuts, `bl_replace_data_output`).
2. Render the bridge vignette (requires `data/tstm_loans_panel.rda` and
   `data/tstm_asset_loan.rda`):
   `pkgdown::build_article("ffv_invest_loan_bridge")`
3. Reload the package so lazy data pick up the new files:
   `devtools::load_all()` or `pkgfast` from the repo root.
4. Re-render this vignette (`ffv_bridge_timing.qmd`).

**Analysis note.** Packaged roster data include three asset ivars
(`agg_BS_1011`, `agg_BS_1012`, `agg_BS_1021`). Below, `ar_ivars` is set to
`agg_BS_1011` only for the timing tables—that is an analysis choice, not the
full ivar set in `data/`.

## Pipeline structure

```{mermaid}
flowchart TD
  subgraph inputs [Packaged gateway outputs]
    roster[tstm_roster_invest2loan2bridge]
    bridges[tstm_loans_bridges_type]
  end
  subgraph prep [Load and merge]
    roster --> merge[merge roster with bridge type and width]
    bridges --> merge
    merge --> filt[filter NA and bridge-only rows]
  end
  subgraph classify [Linkage classifiers]
    filt --> cls[formal-informal triple categories d1m8 d1m5 etc]
  end
  subgraph segment [Bridge segments]
    cls --> bid[construct bridge id with common start at 1]
    bid --> seg[five segmented bridge components]
  end
  subgraph viz [Visualizations]
    seg --> fig[ggplot bridge-timing figures by linkage type]
    fig --> save[optional save to res_bridge_timing]
  end
```

## Load bridge information

Load in all identified bridges, merge with bridge length information.

```{r}
# 1a. Packaged gateway outputs (see "Packaged data inputs" above)
df_roster_invest2loan2bridge <- PrjThaiHFID::tstm_roster_invest2loan2bridge
df_loans_bridges_type <- PrjThaiHFID::tstm_loans_bridges_type
if (verbose) {
  print(glue::glue("f-{it_file_code}, 0bo1"))
  print(glue::glue("{dim(df_roster_invest2loan2bridge)}"))
  print(summary(df_roster_invest2loan2bridge))
  print(glue::glue("{dim(df_loans_bridges_type)}"))
  print(summary(df_loans_bridges_type))
}

# 1b. All investment vars
ar_ivars <- df_roster_invest2loan2bridge %>%
  ungroup() %>%
  distinct(ivars) %>%
  pull(ivars)
ar_ivars <- c("agg_BS_1011")

# 1c. Select and prep bridges_type file variables
# household id, along with loan id for a, b, c loans uniquely identify each row
# in the `df_loans_bridges_type` file.
# get river, abutment, and approach width (see https://github.com/FanWangEcon/PrjThaiHFID/issues/19)
df_loans_bridges_grvabap <- df_loans_bridges_type %>%
  ungroup() %>%
  select(
    hhid_Num,
    hh_loan_id_nd_1t2,
    hh_loan_id_nd_paired_1t2,
    hh_loan_id_nd_paired_2t3,
    ll_grv, ll_gab, ll_gap
  )
# Share stats
df_loans_bridges_grvabap <- df_loans_bridges_grvabap %>%
  mutate(
    ll_grv_share = ll_grv / (ll_grv + ll_gab + ll_gap),
    ll_gab_share = ll_gab / (ll_grv + ll_gab + ll_gap),
    ll_gap_share = ll_gap / (ll_grv + ll_gab + ll_gap),
  )

# 1d. Merge bridge type with roster file
# filter out NA data and bridge only
df_wrk <- df_roster_invest2loan2bridge %>%
  drop_na(forinfm4) %>%
  drop_na(hh_loan_id_nd_paired_1t2) %>%
  drop_na(hh_loan_id_nd_paired_2t3)
df_wrk <- df_wrk %>%
  left_join(
    df_loans_bridges_grvabap,
    by = (c(
      "hhid_Num" = "hhid_Num",
      "hh_loan_id_nd" = "hh_loan_id_nd_1t2",
      "hh_loan_id_nd_paired_1t2" = "hh_loan_id_nd_paired_1t2",
      "hh_loan_id_nd_paired_2t3" = "hh_loan_id_nd_paired_2t3"
    ))
  )
```

## Generate bridge linkage type classifiers

Generate bridge a-b-c for-inf linkage types, depending on definition of formal and informal.

Print all combinations. 
```{r}
# Loan linkage types, at least the number of bridge by the following categories
# # - single lender whole bridge formal only
# bl_bri_only_baac
# bl_bri_only_vilfund
# # - single lender whole bridge informal only
# bl_bri_only_quasi
# bl_bri_only_informal
# # - has informal but not in the middle of the bridge:
# bl_bri_has_informal but not bl_bridge_informal
# # - has informal in middle of bridge: bl_bridge_informal
# bl_bridge_informal
# # Create four categories above
# All big possible categories
if (verbose) {
  print(glue::glue("f-{it_file_code}, 0bo"))
  print(
    df_wrk %>%
      group_by(
        ivars, forinfm4, forinfm4_paired_1t2, forinfm4_paired_2t3
      ) %>% tally() %>%
      group_by(ivars) %>%
      arrange(desc(n)) %>%
      mutate(share = n / sum(n)),
    n = 250
  )
}
```

Generate categories.

```{r}
# 2a. Core triple definition structures redefine formal and informal
# see: file:///C:/Users/fan/UH-ECON%20Dropbox/Fan%20Wang/PrjThaiForInf/PrjThaiHFID/docs/reference/df_roster_invest2loan2bridge.html
# Types of formal and informal linkages:
# 1. formal - formal - formal
# 2. formal - formal - informal
# 3. formal - informal - formal
# 4. formal - informal - informal
# 5. informal - formal - formal
# 6. informal - formal - informal
# 7. informal - informal - formal
# 8. informal - informal - informal
# Grouping the categories above together:
# (a) formal only: 1
# (b) informal only: 8
# (c) informal only middle: 3, meaning informal used as transition from formal to formal
# (d) informal middle +: 4 + 7, meaning informal still used as transition, but transitioning to informal again (informal includes quasiformal)
# (e) formal as transition: 2 + 5 + 6
# d1m8c1: definition 1, multiple categories totalling 8, category 1
# Generate the following variables:
# st_bridge_forinf_d1m8, st_bridge_forinf_d1m5,
# st_bridge_forinf_d2m8, st_bridge_forinf_d2m5,
# st_bridge_forinf_d3m8, st_bridge_forinf_d3m5,
for (it_def in c(1, 2, 3)) {
  if (it_def == 1) {
    ar_for <- c("BAAC-Commercial", "Village-Fund")
    ar_inf <- c("Informal", "Quasi-formal")
  } else if (it_def == 2) {
    ar_for <- c("BAAC-Commercial")
    ar_inf <- c("Village-Fund", "Informal", "Quasi-formal")
  } else if (it_def == 3) {
    ar_for <- c("BAAC-Commercial", "Village-Fund", "Quasi-formal")
    ar_inf <- c("Informal")
  }
  st_var_name_m5 <- paste0("st_bridge_forinf_d", it_def, "m5")
  df_wrk <- df_wrk %>% mutate(
    !!sym(st_var_name_m5) := case_when(
      forinfm4 %in% ar_for & forinfm4_paired_1t2 %in% ar_for & forinfm4_paired_2t3 %in% ar_for ~ "f-f-f",
      forinfm4 %in% ar_for & forinfm4_paired_1t2 %in% ar_for & forinfm4_paired_2t3 %in% ar_inf ~ "f-mid",
      forinfm4 %in% ar_for & forinfm4_paired_1t2 %in% ar_inf & forinfm4_paired_2t3 %in% ar_for ~ "f-i-f",
      forinfm4 %in% ar_for & forinfm4_paired_1t2 %in% ar_inf & forinfm4_paired_2t3 %in% ar_inf ~ "i-mid-i2",
      forinfm4 %in% ar_inf & forinfm4_paired_1t2 %in% ar_for & forinfm4_paired_2t3 %in% ar_for ~ "f-mid",
      forinfm4 %in% ar_inf & forinfm4_paired_1t2 %in% ar_for & forinfm4_paired_2t3 %in% ar_inf ~ "f-mid",
      forinfm4 %in% ar_inf & forinfm4_paired_1t2 %in% ar_inf & forinfm4_paired_2t3 %in% ar_for ~ "i-mid-i2",
      forinfm4 %in% ar_inf & forinfm4_paired_1t2 %in% ar_inf & forinfm4_paired_2t3 %in% ar_inf ~ "i-i-i",
    ),
  )
}

# 2b. Select variables for analysis
# select relevant variables of type and length
df_wrk_sel <- df_wrk %>%
  select(
    hhid_Num, ivars, hh_inv_asset_ctr,
    bl_bridge_informal,
    st_bridge_forinf_d1m5,
    hh_loan_id_nd, hh_loan_id_nd_paired_1t2, hh_loan_id_nd_paired_2t3,
    forinfm4, forinfm4_paired_1t2, forinfm4_paired_2t3,
    loan_start, loan_end,
    loan_start_paired_1t2, loan_end_paired_1t2,
    loan_start_paired_2t3, loan_end_paired_2t3,
    ll_grv, ll_gab, ll_gap,
    ll_grv_share, ll_gab_share, ll_gap_share
  )
if (verbose) {
  print(glue::glue("f-{it_file_code}, a1"))
  print(glue::glue("colnames: {colnames(df_wrk_sel)}"))
  print(glue::glue("df_wrk dim: {dim(df_wrk)}"))
  print(
    df_wrk,
    n = it_row_print
  )
  print(glue::glue("f-{it_file_code}, a2-bag:"))
  print(glue::glue("colnames: {colnames(df_wrk_sel)}"))
  print(glue::glue("df_wrk dim: {dim(df_wrk)}"))
  print(
    df_wrk %>% filter(ll_grv < 0),
    n = it_row_print
  )
}
```

## Sub-selecting dataframe for analysis

Generate data subset using a particular asset variable definition and focused on a particular subset of bridge types. 

```{r}
st_asset_var <- "agg_BS_1011"
# file A
df_wrk_sel_use_bs1011_fif <- df_wrk_sel %>% filter(
  ivars == st_asset_var,
  st_bridge_forinf_d1m5 == "f-i-f"
)
# file B
df_wrk_sel_use_bs1011_fifimidi2 <- df_wrk_sel %>% filter(
  ivars == st_asset_var,
  st_bridge_forinf_d1m5 == "f-i-f" | st_bridge_forinf_d1m5 == "i-mid-i2"
)
# Combine files to list
ls_dataframes_names <- c("bs1011fif", "bs1011fifimidi2")
ls_dataframes <- list(df_wrk_sel_use_bs1011_fif, df_wrk_sel_use_bs1011_fifimidi2)
```

```{r}
# ar_st_forinf_groups <- df_wrk_sel %>% ungroup() %>% distinct(st_bridge_forinf_d1m5) %>% pull(st_bridge_forinf_d1m5)
# Length-5 is just a hint; `[[it_df_ctr]] <-` auto-extends both the list and
# the atomic character vectors when the counter exceeds 5 (assignment grows
# them, it does not error), so adding group variants below is safe.
ls_dataframes <- vector(mode = "list", length = 5)
ls_dataframes_names <- vector(mode = "character", length = 5)
ls_dataframes_notes <- vector(mode = "character", length = 5)
it_df_ctr <- 0
# consider different constructions
ar_st_asset_var <- c("agg_BS_1011")
for (st_asset_var in ar_st_asset_var) {
  ar_st_bridge_forinf <- c("st_bridge_forinf_d1m5", "st_bridge_forinf_d2m5", "st_bridge_forinf_d3m5")
  # Compare the loop variable, not the whole `ar_st_asset_var` vector: an
  # `if()` on a length>1 condition errors in R >= 4.2, so this stays correct
  # if more asset variables are added to `ar_st_asset_var` later.
  if (st_asset_var == "agg_BS_1011") {
    ar_st_bridge_forinf <- c("st_bridge_forinf_d1m5")
  }
  for (st_bridge_forinf in ar_st_bridge_forinf) {
    ar_st_forinf_groups <- c("i-i-i", "f-i-f", "f-f-f", "f-mid", "i-mid-i2")
    if (st_bridge_forinf == "st_bridge_forinf_d1m5") {
      ar_st_forinf_groups <- c(
        "all_groups",
        "i-i-i", "f-i-f", "f-f-f",
        "f-mid", "i-mid-i2"
      )
    }
    for (st_forinf_groups in ar_st_forinf_groups) {
      it_df_ctr <- it_df_ctr + 1
      if (st_forinf_groups == "all_groups") {
        df_wrk_sel_use <- df_wrk_sel %>% filter(
          ivars == st_asset_var
        )
      } else {
        df_wrk_sel_use <- df_wrk_sel %>% filter(
          ivars == st_asset_var,
          !!sym(st_bridge_forinf) == st_forinf_groups
        )
      }
      ls_dataframes[[it_df_ctr]] <- df_wrk_sel_use
      ls_dataframes_names[[it_df_ctr]] <- paste0(st_asset_var, "_", st_bridge_forinf, "_", st_forinf_groups)
      ls_dataframes_notes[[it_df_ctr]] <- paste0(
        "Asset = ", st_asset_var, ", ",
        "Bridge-var = ", st_bridge_forinf, ", ",
        "Bridge-linkage = ", st_forinf_groups
      )
    }
  }
}
```

## Construct bridge ID, common start (at 1), and 5 segmented bridge components

Construct: 

1. Bridge ID, `index_bridge_rvabap_sorted`: these are the sorted index from 1 through N of the number of bridges this particular subset of data contains, these index will be used as values along the y-axis for visualization. 
2. common start, `loan_start_a`, `loan_end_a`, etc: these set the start month to 1, so that when visualized, all bridges start at the same x-axis value of 1. 
3. 5 segmented bridge components, `loan5seg_start_s1`, `loan5seg_end_s1`, etc: these are the start and end of each of the 5 segments of the bridge, the 1st and 5th are non-overlapping components of A and C, 2nd and 4th are overlapping components of A and C with B, and the 3rd is the non-overlapping segment of loan B. 

Note: the Bridge ID sorts loans: `ll_grv, ll_gab, ll_gap` is the sorting order below, this is how the index is organized, "river" length first, "gab" (Abutment) second, "gap" (approach) third. See [Issue-19](https://github.com/FanWangEcon/PrjThaiHFID/issues/19) for definitions of river, abutment, and approach.

```{r}
#' @title Generate Bridge ID and five segments, internal visualizer.
#' @description This function processes a dataframe to generate bridge ID segments for visualization.
#' @param df_wrk_sel A dataframe containing the working selection of data conditional on investment type and subset of bridge types.
#' @param fl_mth_start_shift A numeric value to shift the start month (default is -0.5) for visualization, otherwise 1 month loan does not appear.
#' @param fl_mth_end_shift A numeric value to shift the end month (default is 0.5) for visualization, otherwise 1 month loan does not appear.
#' @return A dataframe with bridge ID segments and additional columns for visualization.
#' @details
#' The function performs the following steps:
#' 1. Generates a bridge index sorted by specific columns and assigns a unique index to each bridge row.
#' 2. Adjusts the start and end month values for different loan periods.
#' 3. Constructs five segments for each bridge and reshapes the dataframe to a long format.
#' 4. Shifts the month values for the start and end of each segment.
#' 5. Generates a group ID for each of the five segments for each bridge.
#' @examples
#' \dontrun{
#' df_result <- ffi_bridge_id_segments(df_wrk_sel)
#' }
ffi_bridge_id_segments <- function(
    df_wrk_sel,
    fl_mth_start_shift = -0.5,
    fl_mth_end_shift = 0.5) {
  # 3a. Generate bridge index sorted by rv ab ap
  # sort ignoring household, but bridge component length only
  # each bridge row should get its own index
  # `index_bridge_rvabap_sorted` is the bridge index, to be plotted along y-axis
  # sorting below decides how bridges are displayed
  df_wrk_sel_use <- df_wrk_sel %>%
    ungroup() %>%
    arrange(
      ll_grv, ll_gab, ll_gap,
      hhid_Num, ivars
    ) %>%
    mutate(index_bridge_rvabap_sorted = row_number())

  # 3b. x-val month start or end, all months start at 1
  df_wrk_vis <- df_wrk_sel_use %>%
    rename(
      loan_start_a = loan_start, loan_end_a = loan_end,
      loan_start_b = loan_start_paired_1t2, loan_end_b = loan_end_paired_1t2,
      loan_start_c = loan_start_paired_2t3, loan_end_c = loan_end_paired_2t3
    ) %>%
    mutate(
      loan_end_a = loan_end_a - loan_start_a + 1,
      loan_start_b = loan_start_b - loan_start_a + 1,
      loan_end_b = loan_end_b - loan_start_a + 1,
      loan_start_c = loan_start_c - loan_start_a + 1,
      loan_end_c = loan_end_c - loan_start_a + 1,
      loan_start_a = loan_start_a - loan_start_a + 1
    )

  # 3c. Construct five segments
  df_wrk_vis_5seg_long <- df_wrk_vis %>%
    mutate(
      loan5seg_start_s1 = loan_start_a,
      loan5seg_end_s1 = loan_start_b,
      loan5seg_start_s2 = loan_start_b,
      loan5seg_end_s2 = loan_end_a,
      loan5seg_start_s3 = loan_end_a,
      loan5seg_end_s3 = loan_start_c,
      loan5seg_start_s4 = loan_start_c,
      loan5seg_end_s4 = loan_end_b,
      loan5seg_start_s5 = loan_end_b,
      loan5seg_end_s5 = loan_end_c
    ) %>%
    select(-contains("loan_start"), -contains("loan_end")) %>%
    pivot_longer(
      cols = starts_with("loan5seg"),
      names_to = c("time", "segment"),
      names_pattern = paste0("loan5seg_(.*)_(.*)"),
      values_to = "month"
    ) %>%
    mutate(month = case_when(
      time == "start" ~ month + fl_mth_start_shift,
      time == "end" ~ month + fl_mth_end_shift
    ))

  # 3e Generate group ID for each of the 5 segments for each of the bridge
  df_wrk_vis_5seg_long <- df_wrk_vis_5seg_long %>%
    group_by(hhid_Num, ivars, index_bridge_rvabap_sorted, segment) %>%
    mutate(graph_group = cur_group_id())
}
```

Use function over generated datasets prior. 

```{r}
ls_dataframes_prc <- vector(mode = "list", length = length(ls_dataframes))
it_file_ctr <- 0
for (df_dataframe in ls_dataframes) {
  it_file_ctr <- it_file_ctr + 1
  df_wrk_sel_prc <- ffi_bridge_id_segments(
    df_dataframe,
    fl_mth_start_shift = -0.5,
    fl_mth_end_shift = 0.5
  )
  ls_dataframes_prc[[it_file_ctr]] <- df_wrk_sel_prc
}
names(ls_dataframes_prc) <- ls_dataframes_names
```

## Generate visualizations 

Coloring, legend, and axis labels and options.

```{r}
# Labels
x_min <- 0
x_max <- 60
x_breaks <- c(
  0,
  6,
  12,
  18,
  24,
  30,
  36,
  48,
  60
)
# colors
ar_st_colours <- c(
  "red",
  "#f28383",
  "blue",
  "#e8ad84",
  "#994205"
)
# Line types
ar_st_linetypes <- c("solid", "dashed", "longdash", "dashed", "solid")
# Legend
ar_st_labels <- c(
  bquote("L-ramp"),
  bquote("L-support"),
  bquote("River"),
  bquote("R-support"),
  bquote("R-ramp")
)
```

Visualize bridges each loan is a five color-segmented line. Bridges are sorted based on Loan B, A, C lengths. We develope a visualization script below.

```{r}
#' Visualize Bridge Loan Data
#'
#' This function creates a ggplot visualization of bridge loan data segmented into five parts.
#'
#' @param df_bridge_5seg_long A data frame containing the bridge loan data with five segments.
#' @param st_title A string for the plot title. Default is "Bridge loan 5 segments".
#' @param st_lab_x A string for the x-axis label. Default is "Months".
#' @param st_lab_y A string for the y-axis label. Default is "Index of bridged loans (sorted by river-length)".
#' @param fl_alpha A numeric value for the transparency level of the lines. Default is 0.70.
#'
#' @return A ggplot object representing the bridge loan data visualization.
#'
#' @examples
#' # Example usage:
#' # df_bridge_5seg_long <- read.csv("path_to_your_data.csv")
#' # plot <- ffi_bridge_visualize(df_bridge_5seg_long)
#' # print(plot)
#'
#' @import ggplot2
#' @import dplyr
#' @import scales
#' @import grid
#' @export
ffi_bridge_visualize <- function(
    df_bridge_5seg_long,
    st_title = "Bridge loan 5 segments",
    st_lab_x = "Months",
    st_lab_y = "Index of bridged loans (sorted by river-length)",
    st_notes = "",
    fl_alpha = 0.70) {
  pl_bridge_roster <- df_bridge_5seg_long %>%
    # filter(index_bridge_rvabap_sorted <= 10) %>%
    ggplot(
      aes(
        x = month,
        y = index_bridge_rvabap_sorted,
        color = segment,
        group = graph_group
      )
    ) +
    geom_line(alpha = fl_alpha)

  # Change segments colors
  pl_bridge_roster <- pl_bridge_roster +
    scale_linetype_manual(
      values = ar_st_linetypes,
      labels = ar_st_labels
    ) +
    scale_colour_manual(
      values = ar_st_colours, labels = ar_st_labels
    )

  pl_bridge_roster <- pl_bridge_roster +
    labs(
      title = st_title,
      x = st_lab_x,
      y = st_lab_y,
      caption = st_notes
    ) +
    scale_x_continuous(
      labels = x_breaks, breaks = x_breaks,
      limits = c(x_min, x_max)
    ) +
    theme_bw() +
    theme(
      legend.title = element_blank(),
      legend.position = c(0.80, 0.15),
      legend.background = element_rect(
        fill = "white",
        colour = "black",
        linetype = "solid"
      ),
      legend.key.width = unit(1.5, "cm"),
      panel.grid.minor.x = element_blank()
    )

  return(pl_bridge_roster)
}
```

We call the visualization script over the dataframes we have construcgted.

```{r}
ls_plot <- vector(mode = "list", length = length(ls_dataframes_prc))
it_file_ctr <- 0
for (df_dataframe_prc in ls_dataframes_prc) {
  it_file_ctr <- it_file_ctr + 1
  pl_cur <- ffi_bridge_visualize(
    df_dataframe_prc,
    st_title = "Bridge loan 5 segments",
    st_lab_x = "Months",
    st_lab_y = "Index of bridged loans (sorted by river-length)",
    st_notes = ls_dataframes_notes[[it_file_ctr]],
    fl_alpha = 0.70
  )
  ls_plot[[it_file_ctr]] <- pl_cur
}
names(ls_plot) <- ls_dataframes_names
```

## Store visualizations 

```{r}
for (nm in names(ls_plot)) {
  pl_fig <- ls_plot[[nm]]

  # On-page display controlled by bl_img_print_on_page (unchanged behavior)
  if (bl_img_print_on_page) {
    print(pl_fig)
  }

  # Disk saving controlled per-figure by ls_save_res (all default FALSE)
  ffp_save_res_figure(
    pl_fig, nm, spt_res,
    bl_save = isTRUE(ls_save_res[[nm]]),
    fl_width = 200, fl_height = 125, it_dpi = 150
  )
}
```