###September 30, 2025
###Graphs for import/deficit values - CHINA

setwd("/Users/katebarnes/Desktop/trabajo/cgd/tariff data/10.04.2025 blog")

#Loading in libraries
library(readxl)
library(dplyr)
library(tidyverse)
library(tidyr)
library(ggplot2)
library(stringr)
library(scales)
library(lubridate)
library(zoo)
library(writexl)
library(patchwork)
library(showtext)

#Loading in census data
census <- read_excel("country.xlsx")

census <- census %>%
  mutate(year = as.numeric(year))

#Filtering out duplicate data
noncountry_groups <- c(
  # Trade agreements / economic blocs / regions
  "Advanced Technology Products", "Africa", "Asia", "Europe", "North America",
  "Australia and Oceania", "Pacific Rim", "South and Central America",
  "European Union", "CAFTA-DR", "North America",
  "NAFTA with Canada (Consump)", "NAFTA with Mexico (Consump)",
  "USMCA with Canada (Consump)", "USMCA with Mexico (Consump)",
  "Sub Saharan Africa",
  # International / special entities
  "International Organizations",
  "World, Not Seasonally Adjusted", "World, Seasonally Adjusted",
  "Unidentified Countries"
)

#Clean + filter
census <- census %>%
  mutate(CTYNAME = str_squish(CTYNAME)) %>% 
  filter(!CTYNAME %in% noncountry_groups)

###CHINA GRAPHS
china <- census %>%
  filter(CTYNAME == "China")



#STYLE FORMATTING

#Add system fonts (including Sofia Pro)
font_add("Sofia Pro", bold = "Sofia Pro Bold Az.otf",
         regular = "Sofia Pro Regular Az.otf",
         italic = "Sofia Pro Light Italic Az.otf")

font_add(
  family = "Sofia Pro Medium",
  regular = "/Users/katebarnes/Downloads/sofia-pro/Sofia Pro Medium Az.otf"
)


#Turn on text rendering
showtext_auto()

#Defining country groups
hic_countries <- c(
  "American Samoa", "Gibraltar", "Panama",
  "Andorra", "Greece", "Poland",
  "Antigua and Barbuda", "Greenland", "Portugal",
  "Aruba", "Guam", "Puerto Rico",
  "Australia", "Guyana", "Qatar",
  "Austria", "Hong Kong SAR, China", "Romania",
  "Bahamas, The", "Hungary", "Russian Federation",
  "Bahrain", "Iceland", "San Marino",
  "Barbados", "Ireland", "Saudi Arabia",
  "Belgium", "Isle of Man", "Seychelles",
  "Bermuda", "Israel", "Singapore",
  "British Virgin Islands", "Italy", "Sint Maarten (Dutch part)",
  "Brunei Darussalam", "Japan", "Slovak Republic",
  "Bulgaria", "Korea, Rep.", "Slovenia",
  "Canada", "Kuwait", "Spain",
  "Cayman Islands", "Latvia", "St. Kitts and Nevis",
  "Channel Islands", "Liechtenstein", "St. Martin (French part)",
  "Chile", "Lithuania", "Sweden",
  "Costa Rica", "Luxembourg", "Switzerland",
  "Croatia", "Macao SAR, China", "Taiwan, China",
  "Curacao", "Malta", "Trinidad and Tobago",
  "Cyprus", "Monaco", "Turks and Caicos Islands",
  "Czechia", "Nauru", "United Arab Emirates",
  "Denmark", "Netherlands", "United Kingdom",
  "Estonia", "New Caledonia", "United States",
  "Faroe Islands", "New Zealand", "Uruguay",
  "Finland", "Northern Mariana Islands", "Virgin Islands (U.S.)",
  "France", "Norway",
  "French Polynesia", "Oman",
  "Germany", "Palau"
)

lic_countries <- c(
  "Afghanistan", "Korea, Dem. People's Rep", "Somalia",
  "Burkina Faso", "Liberia", "South Sudan",
  "Burundi", "Madagascar", "Sudan",
  "Central African Republic", "Malawi", "Syrian Arab Republic",
  "Chad", "Mali", "Togo",
  "Congo, Dem. Rep", "Mozambique", "Uganda",
  "Eritrea", "Niger", "Yemen, Rep.",
  "Gambia, The", "Rwanda",
  "Guinea-Bissau", "Sierra Leone"
)

umic_countries <- c(
  "Albania", "Equatorial Guinea", "Moldova",
  "Algeria", "Fiji", "Mongolia",
  "Argentina", "Gabon", "Montenegro",
  "Armenia", "Georgia", "North Macedonia",
  "Azerbaijan", "Grenada", "Paraguay",
  "Belarus", "Guatemala", "Peru",
  "Belize", "Indonesia", "Samoa",
  "Bosnia and Herzegovina", "Iran, Islamic Rep.", "Serbia",
  "Botswana", "Iraq", "South Africa",
  "Brazil", "Jamaica", "St. Lucia",
  "Cabo Verde", "Kazakhstan", "St. Vincent and the Grenadines",
  "Kosovo", "Suriname",
  "Colombia", "Libya", "Thailand",
  "Cuba", "Malaysia", "Tonga",
  "Dominica", "Maldives", "Türkiye",
  "Dominican Republic", "Marshall Islands", "Turkmenistan",
  "Ecuador", "Mauritius", "Tuvalu",
  "El Salvador", "Mexico", "Ukraine"
)

lmic_countries <- c(
  "Angola", "India", "Papua New Guinea",
  "Bangladesh", "Jordan", "Philippines",
  "Benin", "Kenya", "São Tomé and Principe",
  "Bhutan", "Kiribati", "Senegal",
  "Bolivia", "Kyrgyz Republic", "Solomon Islands",
  "Cambodia", "Lao PDR", "Sri Lanka",
  "Cameroon", "Lebanon", "Tajikistan",
  "Comoros", "Lesotho", "Tanzania",
  "Congo, Rep.", "Mauritania", "Timor-Leste",
  "Côte d'Ivoire", "Micronesia, Fed. Sts.", "Tunisia",
  "Djibouti", "Morocco", "Uzbekistan",
  "Egypt, Arab Rep.", "Myanmar", "Vanuatu",
  "Eswatini", "Namibia", "Viet Nam",
  "Ghana", "Nepal", "West Bank and Gaza",
  "Guinea", "Nicaragua", "Zambia",
  "Haiti", "Nigeria", "Zimbabwe",
  "Honduras", "Pakistan"
)




####
####
####
#### FIGURE 1
uncertain <- read_excel("Categorical_EPU_Data.xlsx")

uncertain$Date <- ymd(uncertain$Date)

start_yr <- as.Date("1990-01-01")
end_yr   <- ceiling_date(max(uncertain$Date, na.rm = TRUE), "year")

#Saving data to Excel
write_xlsx(uncertain, "Figure1_data.xlsx")

ggplot(uncertain, aes(x = Date, y = `Trade policy`)) +
  geom_line(linewidth = 1.2, color = "#006970") +
  scale_x_date(
    breaks = seq(start_yr, end_yr, by = "2 years"),
    labels = label_date("%Y"))  +
  labs(
    title   = "Figure 1: Monthly U.S. Trade Policy Uncertainty Index",
    x = NULL,
    y = NULL,
    caption = "Source: Economic Policy Uncertainty"
  ) +
  theme_minimal(base_family = "Sofia Pro") +
  theme(
    panel.grid = element_blank(),  # remove ALL grid lines
    plot.title   = element_text(family = "Sofia Pro", face = "bold",  size = 18, hjust = 0.5),
    plot.caption = element_text(family = "Sofia Pro Medium", size = 10, hjust = 0.5),
    axis.title   = element_text(family = "Sofia Pro Medium", size = 12),
    legend.position = "none"
  )






###########
###########
###########
###########
###########
####FIGURE 2 DATA
#Reshaping China data
china_annual <- china %>%
  filter(str_detect(CTYNAME, regex("^China", ignore_case = TRUE))) %>%
  filter(year >= 2017, year <= 2024) %>%
  transmute(
    year,
    imports = as.numeric(IYR),
    exports = as.numeric(EYR),
    deficit = imports - exports,
    deficit_mag   = abs(deficit)
  )

#Sanity check to prep for indexing
stopifnot(2018 %in% china_annual$year)

#Creating index
base_imports  <- china_annual %>% filter(year == 2018) %>% pull(imports) %>% first()
base_deficit  <- china_annual %>% filter(year == 2018) %>% pull(deficit) %>% first()
base_defmag  <- china_annual %>% filter(year == 2018) %>% pull(deficit_mag)


china_idx <- china_annual %>%
  mutate(
    imports_index = 100 * imports / base_imports,
    deficit_index = ifelse(base_deficit == 0, NA_real_, 100 * deficit / base_deficit)
  ) %>%
  select(year, imports_index, deficit_index) %>%
  pivot_longer(-year, names_to = "series", values_to = "index") %>%
  mutate(
    series = recode(series,
                    imports_index = "US imports from China",
                    deficit_index = "US trade deficit with China"
    )
  )

#Creating graph

china_idx <- china_annual %>%
  transmute(
    year = as.numeric(year),
    `US imports from China`        = 100 * imports     / base_imports,
    `US trade deficit with China`  = 100 * deficit_mag / base_defmag
  ) %>%
  pivot_longer(-year, names_to = "series", values_to = "index")

#Saving data to Excel
write_xlsx(china_idx, "Figure2_data.xlsx")

ggplot(china_idx, aes(x = year, y = index, color = series)) +
  geom_line(linewidth = 1.2) +
  geom_point(size = 2.2) +
  scale_x_continuous(breaks = 2017:2024, limits = c(2017, 2024)) +
  scale_y_continuous(labels = label_number(accuracy = 10)) +
  geom_hline(yintercept = 100, linetype = "dashed", color = "gray40") +
  scale_color_manual(
    values = c(
      "US imports from China"        = "#006970",  # line 1
      "US trade deficit with China"  = "#FFB52C"   # line 2
    ),
    breaks = c("US imports from China", "US trade deficit with China"),  # legend order
    guide = guide_legend(title = NULL)
  ) +
  labs(
    title = "Figure 2: U.S. Imports from China & Trade Deficit (Annual Index, 2018 = 100)",
    subtitle = "Annual, 2017–2024",
    x = "Year",
    y = "Index (2018 = 100)",
    caption = "Source: U.S. Census Bureau"
  ) +
  theme_minimal(base_family = "Sofia Pro") +
  theme(
    #Titles
    plot.title   = element_text(family = "Sofia Pro", face = "bold",   size = 20, hjust = 0.5),
    plot.subtitle= element_text(family = "Sofia Pro", face = "italic", size = 15, hjust = 0.5),
    
    #Axes
    axis.title   = element_text(family = "Sofia Pro Medium", size = 12),
    
    #Grid/Panel
    panel.grid.minor = element_blank(),
    
    #Legend
    legend.position = "bottom",
    legend.text     = element_text(family = "Sofia Pro", size = 15)
  )








###########
###########
###########
###########
###########
#FIGURE 3 NEW
month_levels <- c("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC")

china_only <- c(
  "China")

group7_monthly_all <- census %>%
  mutate(year = as.numeric(as.character(year))) %>%
  filter(CTYNAME %in% china_only, year %in% 2023:2025) %>%
  select(year, CTYNAME, matches("^[IE][A-Z]{3}$")) %>%
  pivot_longer(
    -c(year, CTYNAME),
    names_to   = c("flow","mon"),
    names_pattern = "^([IE])([A-Z]{3})$",
    values_to  = "value"
  ) %>%
  mutate(
    flow = if_else(flow == "I", "imports", "exports"),
    mon  = factor(mon, levels = month_levels),
    mnum = as.integer(mon),
    date = as.Date(sprintf("%04d-%02d-01", year, mnum)),
    value = as.numeric(value)
  ) %>%
  filter(flow == "imports") %>%
  group_by(year, mnum, date) %>%
  summarise(imports = sum(value, na.rm = TRUE), .groups = "drop") %>%
  arrange(date)

#Cumulative YoY (YTD)
group7_cumyoy_all <- group7_monthly_all %>%
  group_by(year) %>%
  arrange(mnum, .by_group = TRUE) %>%
  mutate(cum_imports = cumsum(imports)) %>%
  ungroup() %>%
  select(year, mnum, date, cum_imports) %>%
  {
    df <- .
    prior <- df %>%
      transmute(
        year = year + 1L,      # align prior-year YTD to current year
        mnum,
        cum_imports_prev = cum_imports
      )
    left_join(df, prior, by = c("year","mnum"))
  } %>%
  mutate(
    cumyoy_imports_pct = if_else(
      is.na(cum_imports_prev) | cum_imports_prev == 0,
      NA_real_,
      100 * (cum_imports / cum_imports_prev - 1)
    )
  )

#Split series
series_2024 <- group7_cumyoy_all %>% filter(year == 2024)

series_2025 <- group7_cumyoy_all %>%
  filter(year == 2025, date <= as.Date("2025-07-01")) %>%
  filter(date <= max(date, na.rm = TRUE))

#Common y-axis
ymin <- min(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)
ymax <- max(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)
ymin <- floor(ymin - 1)
ymax <- ceiling(ymax + 1)

#Saving data to Excel
write_xlsx(series_2024, "Figure3_2024_data.xlsx")

#Plots
p_2024 <- ggplot(series_2024, aes(x = date, y = cumyoy_imports_pct)) +
  geom_line(linewidth = 1.2, color = "#006970") +
  geom_point(size = 2.2, color = "#006970") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray40") +
  scale_x_date(
    breaks = seq(as.Date("2024-01-01"), as.Date("2024-12-01"), by = "1 month"),
    labels = label_date("%b"),
    limits = c(as.Date("2024-01-01"), as.Date("2024-12-31"))
  ) +
  scale_y_continuous(
    limits = c(ymin, ymax),
    labels = label_number(accuracy = 0.1, suffix = "%"),
    minor_breaks = NULL
  ) +
  labs(
    title = "2024",
    x = NULL, y = "Cumulative YoY %"
  ) +
  theme_minimal(base_family = "Sofia Pro") +
  theme(
    plot.title   = element_text(family = "Sofia Pro", face = "bold", size = 18, hjust = 0.5),
    axis.title   = element_text(family = "Sofia Pro Medium", size = 12),
    panel.grid.minor = element_blank(),
    legend.position = "none"
  )

#Saving data to Excel
write_xlsx(series_2025, "Figure3_2025_data.xlsx")

p_2025 <- ggplot(series_2025, aes(x = date, y = cumyoy_imports_pct)) +
  geom_line(linewidth = 1.2, color = "#006970") +
  geom_point(size = 2.2, color = "#006970") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray40") +
  scale_x_date(
    breaks = seq(as.Date("2025-01-01"), max(series_2025$date, na.rm = TRUE), by = "1 month"),
    labels = label_date("%b"),
    limits = c(as.Date("2025-01-01"), max(series_2025$date, na.rm = TRUE))
  ) +
  scale_y_continuous(
    limits = c(ymin, ymax),
    labels = label_number(accuracy = 0.1, suffix = "%"),
    minor_breaks = NULL
  ) +
  labs(
    title = "2025",
    x = NULL, y = "Cumulative YoY %"
  ) +
  theme_minimal(base_family = "Sofia Pro") +
  theme(
    plot.title   = element_text(family = "Sofia Pro", face = "bold", size = 18, hjust = 0.5),
    axis.title   = element_text(family = "Sofia Pro Medium", size = 12),
    panel.grid.minor = element_blank(),
    legend.position = "none"
  )

#Side-by-side with styled header
(p_2024 | p_2025) +
  plot_annotation(
    title = "Figure 3: U.S. Imports from China — Cumulative YoY %",
    subtitle = "Left: Full-year 2024 • Right: 2025 YTD",
    caption = "Source: U.S. Census Bureau",
    theme = theme(
      plot.title    = element_text(family = "Sofia Pro", face = "bold",   size = 22, hjust = 0.5),
      plot.subtitle = element_text(family = "Sofia Pro", face = "italic", size = 14, hjust = 0.5),
      plot.caption  = element_text(family = "Sofia Pro Medium",           size = 10, hjust = 0.5)
    )
  )










###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########FIGURE 4: World minus China YoY Cumm YTD
month_levels <- c("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC")

valid_countries <- c(
  "Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla",
  "Antigua and Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan",
  "Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda",
  "Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Brazil",
  "British Indian Ocean Territory","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burma","Burundi",
  "Cabo Verde","Cambodia","Cameroon","Canada","Cayman Islands","Central African Republic","Chad","Chile",
  "Christmas Island","Cocos (Keeling) Islands","Colombia","Comoros","Congo","Cook Islands","Costa Rica","Cote d'Ivoire",
  "Croatia","Cuba","Curacao","Cyprus","Czech Republic",
  "Democratic Republic of Congo","Denmark","Djibouti","Dominica","Dominican Republic",
  "East Timor","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Eswatini","Ethiopia",
  "Falkland Islands","Faroe Islands","Fiji","Finland","France","French Guiana","French Polynesia","French Southern and Antarctic Lands",
  "Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guadeloupe","Guatemala","Guinea","Guinea-Bissau","Guyana",
  "Haiti","Heard and McDonald Islands","Honduras","Hong Kong","Hungary",
  "Iceland","India","Indonesia","Iran","Iraq","Ireland","Israel","Italy",
  "Jamaica","Japan","Jordan",
  "Kazakhstan","Kenya","Kiribati","Korea, North","Korea, South","Kosovo","Kuwait","Kyrgyzstan",
  "Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg",
  "Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Martinique",
  "Mauritania","Mauritius","Mayotte","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique",
  "Namibia","Nauru","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","Niue","Norfolk Island","Norway",
  "Oman",
  "Pakistan","Palau","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Pitcairn Islands","Poland","Portugal",
  "Qatar",
  "Republic of Yemen","Reunion","Romania","Russia","Rwanda",
  "Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Sint Maarten",
  "Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Sudan","Spain","Sri Lanka",
  "St Helena","St Kitts and Nevis","St Lucia","St Pierre and Miquelon","St Vincent and the Grenadines","Sudan","Suriname",
  "Svalbard, Jan Mayen Island","Sweden","Switzerland","Syria",
  "Taiwan","Tajikistan","Tanzania","Thailand","Togo","Tokelau","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Turks and Caicos Islands","Tuvalu",
  "Uganda","Ukraine","United Arab Emirates","United Kingdom","Uruguay","Uzbekistan",
  "Vanuatu","Vatican City","Venezuela","Vietnam",
  "Wallis and Futuna","Western Sahara",
  "Zambia","Zimbabwe"
)


group7_monthly_all <- census %>%
  mutate(year = as.numeric(as.character(year))) %>%
  filter(CTYNAME %in% valid_countries, year %in% 2023:2025) %>%
  select(year, CTYNAME, matches("^[IE][A-Z]{3}$")) %>%
  pivot_longer(
    -c(year, CTYNAME),
    names_to   = c("flow","mon"),
    names_pattern = "^([IE])([A-Z]{3})$",
    values_to  = "value"
  ) %>%
  mutate(
    flow = if_else(flow == "I", "imports", "exports"),
    mon  = factor(mon, levels = month_levels),
    mnum = as.integer(mon),
    date = as.Date(sprintf("%04d-%02d-01", year, mnum)),
    value = as.numeric(value)
  ) %>%
  filter(flow == "imports") %>%
  group_by(year, mnum, date) %>%
  summarise(imports = sum(value, na.rm = TRUE), .groups = "drop") %>%
  arrange(date)

#Cumulative YoY (YTD)
group7_cumyoy_all <- group7_monthly_all %>%
  group_by(year) %>%
  arrange(mnum, .by_group = TRUE) %>%
  mutate(cum_imports = cumsum(imports)) %>%
  ungroup() %>%
  select(year, mnum, date, cum_imports) %>%
  {
    df <- .
    prior <- df %>%
      transmute(
        year = year + 1L,
        mnum,
        cum_imports_prev = cum_imports
      )
    left_join(df, prior, by = c("year","mnum"))
  } %>%
  mutate(
    cumyoy_imports_pct = if_else(
      is.na(cum_imports_prev) | cum_imports_prev == 0,
      NA_real_,
      100 * (cum_imports / cum_imports_prev - 1)
    )
  )

#Split Series
series_2024 <- group7_cumyoy_all %>% filter(year == 2024)

series_2025 <- group7_cumyoy_all %>%
  filter(year == 2025, date <= as.Date("2025-07-01")) %>%
  filter(date <= max(date, na.rm = TRUE))

#Common y-axis
ymin <- min(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)
ymax <- max(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)
ymin <- floor(ymin - 1)
ymax <- ceiling(ymax + 1)

#Saving data to Excel
write_xlsx(series_2024, "Figure4_2024_data.xlsx")

#Plots (styled like yesterday)
p_2024 <- ggplot(series_2024, aes(x = date, y = cumyoy_imports_pct)) +
  geom_line(linewidth = 1.2, color = "#006970") +
  geom_point(size = 2.2, color = "#006970") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray40") +
  scale_x_date(
    breaks = seq(as.Date("2024-01-01"), as.Date("2024-12-01"), by = "1 month"),
    labels = label_date("%b"),
    limits = c(as.Date("2024-01-01"), as.Date("2024-12-31"))
  ) +
  scale_y_continuous(
    limits = c(ymin, ymax),
    labels = label_number(accuracy = 0.1, suffix = "%"),
    minor_breaks = NULL
  ) +
  labs(
    title = "2024",
    x = NULL, y = "Cumulative YoY %"
  ) +
  theme_minimal(base_family = "Sofia Pro") +
  theme(
    plot.title   = element_text(family = "Sofia Pro", face = "bold",   size = 18, hjust = 0.5),
    axis.title   = element_text(family = "Sofia Pro Medium",           size = 12),
    panel.grid.minor = element_blank(),
    legend.position = "none"
  )

#Saving data to Excel
write_xlsx(series_2024, "Figure4_2025_data.xlsx")

p_2025 <- ggplot(series_2025, aes(x = date, y = cumyoy_imports_pct)) +
  geom_line(linewidth = 1.2, color = "#006970") +
  geom_point(size = 2.2, color = "#006970") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray40") +
  scale_x_date(
    breaks = seq(as.Date("2025-01-01"), max(series_2025$date, na.rm = TRUE), by = "1 month"),
    labels = label_date("%b"),
    limits = c(as.Date("2025-01-01"), max(series_2025$date, na.rm = TRUE))
  ) +
  scale_y_continuous(
    limits = c(ymin, ymax),
    labels = label_number(accuracy = 0.1, suffix = "%"),
    minor_breaks = NULL
  ) +
  labs(
    title = "2025",
    x = NULL, y = "Cumulative YoY %"
  ) +
  theme_minimal(base_family = "Sofia Pro") +
  theme(
    plot.title   = element_text(family = "Sofia Pro", face = "bold",   size = 18, hjust = 0.5),
    axis.title   = element_text(family = "Sofia Pro Medium",           size = 12),
    panel.grid.minor = element_blank(),
    legend.position = "none"
  )

#Side-by-side with styled header
(p_2024 | p_2025) +
  plot_annotation(
    title    = "Figure 4: U.S. Imports from the World (Excluding China) — Cumulative YoY %",
    subtitle = "Left: Full-year 2024 • Right: 2025 YTD",
    caption  = "Source: U.S. Census Bureau",
    theme = theme(
      plot.title    = element_text(family = "Sofia Pro",        face = "bold",   size = 22, hjust = 0.5),
      plot.subtitle = element_text(family = "Sofia Pro",        face = "italic", size = 14, hjust = 0.5),
      plot.caption  = element_text(family = "Sofia Pro Medium",                  size = 10, hjust = 0.5)
    )
  )








##### FIGURE 5 (AGGREGATED)
library(ggplot2)
library(scales)
library(patchwork)
library(dplyr)
library(tidyr)

#Graph 6: Vietnam, Thailand, Indonesia (Cumulative YoY, Imports)
month_levels <- c("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC")

viet_indo_thai <- c(
  "Vietnam", "Thailand", "Indonesia", "Taiwan"
)

group7_monthly_all <- census %>%
  mutate(year = as.numeric(as.character(year))) %>%
  filter(CTYNAME %in% viet_indo_thai, year %in% 2023:2025) %>%
  select(year, CTYNAME, matches("^[IE][A-Z]{3}$")) %>%
  pivot_longer(
    -c(year, CTYNAME),
    names_to   = c("flow","mon"),
    names_pattern = "^([IE])([A-Z]{3})$",
    values_to  = "value"
  ) %>%
  mutate(
    flow = if_else(flow == "I", "imports", "exports"),
    mon  = factor(mon, levels = month_levels),
    mnum = as.integer(mon),
    date = as.Date(sprintf("%04d-%02d-01", year, mnum)),
    value = as.numeric(value)
  ) %>%
  filter(flow == "imports") %>%
  group_by(year, mnum, date) %>%                                   # aggregates 3 countries
  summarise(imports = sum(value, na.rm = TRUE), .groups = "drop") %>%
  arrange(date)

#Cumulative YoY (YTD)
group7_cumyoy_all <- group7_monthly_all %>%
  group_by(year) %>%
  arrange(mnum, .by_group = TRUE) %>%
  mutate(cum_imports = cumsum(imports)) %>%
  ungroup() %>%
  select(year, mnum, date, cum_imports) %>%
  {
    df <- .
    prior <- df %>%
      transmute(
        year = year + 1L,
        mnum,
        cum_imports_prev = cum_imports
      )
    left_join(df, prior, by = c("year","mnum"))
  } %>%
  mutate(
    cumyoy_imports_pct = if_else(
      is.na(cum_imports_prev) | cum_imports_prev == 0,
      NA_real_,
      100 * (cum_imports / cum_imports_prev - 1)
    )
  )

#Split series
series_2024 <- group7_cumyoy_all %>% filter(year == 2024)
series_2025 <- group7_cumyoy_all %>%
  filter(year == 2025, date <= as.Date("2025-07-01")) %>%
  filter(date <= max(date, na.rm = TRUE))

#Common y-axis
ymin <- min(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)
ymax <- max(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)
ymin <- floor(ymin - 1)
ymax <- ceiling(ymax + 1)

#Saving data to Excel
write_xlsx(series_2024, "Figure5A_2024_data.xlsx")

#Plots (styled like yesterday)
p_2024 <- ggplot(series_2024, aes(x = date, y = cumyoy_imports_pct)) +
  geom_line(linewidth = 1.2, color = "#006970") +
  geom_point(size = 2.2, color = "#006970") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray40") +
  scale_x_date(
    breaks = seq(as.Date("2024-01-01"), as.Date("2024-12-01"), by = "1 month"),
    labels = label_date("%b"),
    limits = c(as.Date("2024-01-01"), as.Date("2024-12-31"))
  ) +
  scale_y_continuous(
    limits = c(ymin, ymax),
    labels = label_number(accuracy = 0.1, suffix = "%"),
    minor_breaks = NULL
  ) +
  labs(
    title = "2024",
    x = NULL, y = "Cumulative YoY %"
  ) +
  theme_minimal(base_family = "Sofia Pro") +
  theme(
    plot.title   = element_text(family = "Sofia Pro", face = "bold",   size = 18, hjust = 0.5),
    axis.title   = element_text(family = "Sofia Pro Medium",           size = 12),
    panel.grid.minor = element_blank(),
    legend.position = "none"
  )

#Saving data to Excel
write_xlsx(series_2025, "Figure5A_2025_data.xlsx")

p_2025 <- ggplot(series_2025, aes(x = date, y = cumyoy_imports_pct)) +
  geom_line(linewidth = 1.2, color = "#006970") +
  geom_point(size = 2.2, color = "#006970") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray40") +
  scale_x_date(
    breaks = seq(as.Date("2025-01-01"), max(series_2025$date, na.rm = TRUE), by = "1 month"),
    labels = label_date("%b"),
    limits = c(as.Date("2025-01-01"), max(series_2025$date, na.rm = TRUE))
  ) +
  scale_y_continuous(
    limits = c(ymin, ymax),
    labels = label_number(accuracy = 0.1, suffix = "%"),
    minor_breaks = NULL
  ) +
  labs(
    title = "2025",
    x = NULL, y = "Cumulative YoY %"
  ) +
  theme_minimal(base_family = "Sofia Pro") +
  theme(
    plot.title   = element_text(family = "Sofia Pro", face = "bold",   size = 18, hjust = 0.5),
    axis.title   = element_text(family = "Sofia Pro Medium",           size = 12),
    panel.grid.minor = element_blank(),
    legend.position = "none"
  )

#Side-by-side with styled header
(p_2024 | p_2025) +
  plot_annotation(
    title    = "Figure 5: U.S. Imports from Vietnam, Thailand, Indonesia, and Taiwan  — Cumulative YoY %",
    subtitle = "Left: Full-year 2024 • Right: 2025 YTD",
    caption  = "Source: U.S. Census Bureau",
    theme = theme(
      plot.title    = element_text(family = "Sofia Pro",        face = "bold",   size = 22, hjust = 0.5),
      plot.subtitle = element_text(family = "Sofia Pro",        face = "italic", size = 14, hjust = 0.5),
      plot.caption  = element_text(family = "Sofia Pro Medium",                  size = 10, hjust = 0.5)
    )
  )













#####
#####
#####
#####
#####
#####
#####
##### FIGURE 5 (INDIVIDUAL)
vtit_countries <- c("Vietnam","Thailand","Indonesia","Taiwan")

month_levels <- c("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC")

group7_monthly_all <- census %>%
  mutate(year = as.numeric(as.character(year))) %>%
  filter(CTYNAME %in% vtit_countries, year %in% 2023:2025) %>%
  select(year, CTYNAME, matches("^[IE][A-Z]{3}$")) %>%
  pivot_longer(
    -c(year, CTYNAME),
    names_to   = c("flow","mon"),
    names_pattern = "^([IE])([A-Z]{3})$",
    values_to  = "value"
  ) %>%
  mutate(
    flow = if_else(flow == "I", "imports", "exports"),
    mon  = factor(mon, levels = month_levels),
    mnum = as.integer(mon),
    date = as.Date(sprintf("%04d-%02d-01", year, mnum)),
    value = as.numeric(value)
  ) %>%
  filter(flow == "imports") %>%
  group_by(CTYNAME, year, mnum, date) %>%                        # keep CTYNAME to avoid aggregation
  summarise(imports = sum(value, na.rm = TRUE), .groups = "drop") %>%
  arrange(CTYNAME, date)

#Cumulative YoY (YTD) per country
group7_cumyoy_all <- group7_monthly_all %>%
  group_by(CTYNAME, year) %>%
  arrange(mnum, .by_group = TRUE) %>%
  mutate(cum_imports = cumsum(imports)) %>%
  ungroup() %>%
  select(CTYNAME, year, mnum, date, cum_imports) %>%
  {
    df <- .
    prior <- df %>%
      transmute(
        CTYNAME,
        year = year + 1L,            # align prior-year YTD to current year
        mnum,
        cum_imports_prev = cum_imports
      )
    left_join(df, prior, by = c("CTYNAME","year","mnum"))
  } %>%
  mutate(
    cumyoy_imports_pct = if_else(
      is.na(cum_imports_prev) | cum_imports_prev == 0,
      NA_real_,
      100 * (cum_imports / cum_imports_prev - 1)
    )
  )

#Split series
series_2024 <- group7_cumyoy_all %>% filter(year == 2024)
series_2025 <- group7_cumyoy_all %>%
  filter(year == 2025, date <= as.Date("2025-07-01")) %>%
  filter(date <= max(date, na.rm = TRUE))

#Common y-axis across both panels
ymin <- min(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)
ymax <- max(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)
ymin <- floor(ymin - 1)
ymax <- ceiling(ymax + 1)

#Color mapping (adjust if you prefer different hues)
country_cols <- c(
  "Vietnam"   = "#006970",  # teal
  "Thailand"  = "#FFB52C",  # gold
  "Indonesia" = "#00394D",  # deep teal/blue
  "Taiwan"    = "#7A9E9F"   # soft blue-gray
)


#Saving data to Excel
write_xlsx(series_2024, "Figure5B_2024_data.xlsx")

#Plots
p_2024 <- ggplot(series_2024, aes(x = date, y = cumyoy_imports_pct, color = CTYNAME)) +
  geom_line(linewidth = 1.2) +
  geom_point(size = 2.2) +
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray40") +
  scale_x_date(
    breaks = seq(as.Date("2024-01-01"), as.Date("2024-12-01"), by = "1 month"),
    labels = label_date("%b"),
    limits = c(as.Date("2024-01-01"), as.Date("2024-12-31"))
  ) +
  scale_y_continuous(limits = c(ymin, ymax), labels = label_number(accuracy = 0.1, suffix = "%"), minor_breaks = NULL) +
  scale_color_manual(values = country_cols, guide = guide_legend(title = NULL)) +
  labs(title = "2024", x = NULL, y = "Cumulative YoY %") +
  theme_minimal(base_family = "Sofia Pro") +
  theme(
    plot.title   = element_text(family = "Sofia Pro", face = "bold", size = 18, hjust = 0.5),
    axis.title   = element_text(family = "Sofia Pro Medium", size = 12),
    panel.grid.minor = element_blank()
  ) +
  theme(legend.position = "bottom")

#Saving data to Excel
write_xlsx(series_2024, "Figure5B_2025_data.xlsx")

p_2025 <- ggplot(series_2025, aes(x = date, y = cumyoy_imports_pct, color = CTYNAME)) +
  geom_line(linewidth = 1.2) +
  geom_point(size = 2.2) +
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray40") +
  scale_x_date(
    breaks = seq(as.Date("2025-01-01"), max(series_2025$date, na.rm = TRUE), by = "1 month"),
    labels = label_date("%b"),
    limits = c(as.Date("2025-01-01"), max(series_2025$date, na.rm = TRUE))
  ) +
  scale_y_continuous(limits = c(ymin, ymax), labels = label_number(accuracy = 0.1, suffix = "%"), minor_breaks = NULL) +
  scale_color_manual(values = country_cols, guide = guide_legend(title = NULL)) +
  labs(title = "2025", x = NULL, y = "Cumulative YoY %") +
  theme_minimal(base_family = "Sofia Pro") +
  theme(
    plot.title   = element_text(family = "Sofia Pro", face = "bold", size = 18, hjust = 0.5),
    axis.title   = element_text(family = "Sofia Pro Medium", size = 12),
    panel.grid.minor = element_blank()
  ) +
  theme(legend.position = "bottom")

#Side-by-side with shared legend + styled header
combined <- (p_2024 | p_2025) +
  plot_layout(guides = "collect") +
  plot_annotation(
    title    = "Figure 5: U.S. Imports — Cumulative YoY %\nVietnam, Thailand, Indonesia, and Taiwan",
    subtitle = "Left: Full-year 2024 • Right: 2025 YTD",
    caption  = "Source: U.S. Census Bureau"
  )

combined &
  theme(
    legend.position = "bottom",
    legend.text     = element_text(family = "Sofia Pro", size = 12),
    
    # Annotation & plot text styling
    plot.title      = element_text(family = "Sofia Pro", face = "bold",   size = 22, hjust = 0.5),
    plot.subtitle   = element_text(family = "Sofia Pro", face = "italic", size = 14, hjust = 0.5),
    plot.caption    = element_text(family = "Sofia Pro Medium",           size = 10, hjust = 0.5)
  )











#####
#####
#####
#####
#####
#####
#####
##### FIGURE 6

#Defining country groups
hic_countries <- c(
  "American Samoa", "Gibraltar", "Panama",
  "Andorra", "Greece", "Poland",
  "Antigua and Barbuda", "Greenland", "Portugal",
  "Aruba", "Guam", "Puerto Rico",
  "Australia", "Guyana", "Qatar",
  "Austria", "Hong Kong SAR, China", "Romania",
  "Bahamas, The", "Hungary", "Russian Federation",
  "Bahrain", "Iceland", "San Marino",
  "Barbados", "Ireland", "Saudi Arabia",
  "Belgium", "Isle of Man", "Seychelles",
  "Bermuda", "Israel", "Singapore",
  "British Virgin Islands", "Italy", "Sint Maarten (Dutch part)",
  "Brunei Darussalam", "Japan", "Slovak Republic",
  "Bulgaria", "Korea, Rep.", "Slovenia",
  "Canada", "Kuwait", "Spain",
  "Cayman Islands", "Latvia", "St. Kitts and Nevis",
  "Channel Islands", "Liechtenstein", "St. Martin (French part)",
  "Chile", "Lithuania", "Sweden",
  "Costa Rica", "Luxembourg", "Switzerland",
  "Croatia", "Macao SAR, China", "Taiwan, China",
  "Curacao", "Malta", "Trinidad and Tobago",
  "Cyprus", "Monaco", "Turks and Caicos Islands",
  "Czechia", "Nauru", "United Arab Emirates",
  "Denmark", "Netherlands", "United Kingdom",
  "Estonia", "New Caledonia", "United States",
  "Faroe Islands", "New Zealand", "Uruguay",
  "Finland", "Northern Mariana Islands", "Virgin Islands (U.S.)",
  "France", "Norway",
  "French Polynesia", "Oman",
  "Germany", "Palau"
)

lic_countries <- c(
  "Afghanistan", "Korea, Dem. People's Rep", "Somalia",
  "Burkina Faso", "Liberia", "South Sudan",
  "Burundi", "Madagascar", "Sudan",
  "Central African Republic", "Malawi", "Syrian Arab Republic",
  "Chad", "Mali", "Togo",
  "Congo, Dem. Rep", "Mozambique", "Uganda",
  "Eritrea", "Niger", "Yemen, Rep.",
  "Gambia, The", "Rwanda",
  "Guinea-Bissau", "Sierra Leone"
)

umic_countries <- c(
  "Albania", "Equatorial Guinea", "Moldova",
  "Algeria", "Fiji", "Mongolia",
  "Argentina", "Gabon", "Montenegro",
  "Armenia", "Georgia", "North Macedonia",
  "Azerbaijan", "Grenada", "Paraguay",
  "Belarus", "Guatemala", "Peru",
  "Belize", "Indonesia", "Samoa",
  "Bosnia and Herzegovina", "Iran, Islamic Rep.", "Serbia",
  "Botswana", "Iraq", "South Africa",
  "Brazil", "Jamaica", "St. Lucia",
  "Cabo Verde", "Kazakhstan", "St. Vincent and the Grenadines",
  "Kosovo", "Suriname",
  "Colombia", "Libya", "Thailand",
  "Cuba", "Malaysia", "Tonga",
  "Dominica", "Maldives", "Türkiye",
  "Dominican Republic", "Marshall Islands", "Turkmenistan",
  "Ecuador", "Mauritius", "Tuvalu",
  "El Salvador", "Mexico", "Ukraine"
)

lmic_countries <- c(
  "Angola", "India", "Papua New Guinea",
  "Bangladesh", "Jordan", "Philippines",
  "Benin", "Kenya", "São Tomé and Principe",
  "Bhutan", "Kiribati", "Senegal",
  "Bolivia", "Kyrgyz Republic", "Solomon Islands",
  "Cambodia", "Lao PDR", "Sri Lanka",
  "Cameroon", "Lebanon", "Tajikistan",
  "Comoros", "Lesotho", "Tanzania",
  "Congo, Rep.", "Mauritania", "Timor-Leste",
  "Côte d'Ivoire", "Micronesia, Fed. Sts.", "Tunisia",
  "Djibouti", "Morocco", "Uzbekistan",
  "Egypt, Arab Rep.", "Myanmar", "Vanuatu",
  "Eswatini", "Namibia", "Viet Nam",
  "Ghana", "Nepal", "West Bank and Gaza",
  "Guinea", "Nicaragua", "Zambia",
  "Haiti", "Nigeria", "Zimbabwe",
  "Honduras", "Pakistan"
)


###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
#Graph 1: HICs
month_levels <- c("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC")

group7_monthly_all <- census %>%
  mutate(year = as.numeric(as.character(year))) %>%
  filter(CTYNAME %in% hic_countries, year %in% 2023:2025) %>%
  select(year, CTYNAME, matches("^[IE][A-Z]{3}$")) %>%
  pivot_longer(
    -c(year, CTYNAME),
    names_to   = c("flow","mon"),
    names_pattern = "^([IE])([A-Z]{3})$",
    values_to  = "value"
  ) %>%
  mutate(
    flow = if_else(flow == "I", "imports", "exports"),
    mon  = factor(mon, levels = month_levels),
    mnum = as.integer(mon),
    date = as.Date(sprintf("%04d-%02d-01", year, mnum)),
    value = as.numeric(value)
  ) %>%
  filter(flow == "imports") %>%
  group_by(year, mnum, date) %>%
  summarise(imports = sum(value, na.rm = TRUE), .groups = "drop") %>%
  arrange(date)

#Helper: compute cumulative YoY (YTD) for imports for all years in table
group7_cumyoy_all <- group7_monthly_all %>%
  group_by(year) %>%
  arrange(mnum, .by_group = TRUE) %>%
  mutate(cum_imports = cumsum(imports)) %>%
  ungroup() %>%
  select(year, mnum, date, cum_imports) %>%
  {
    df <- .
    prior <- df %>%
      transmute(
        year = year + 1L,          # align prior-year YTD to current year
        mnum,
        cum_imports_prev = cum_imports
      )
    left_join(df, prior, by = c("year","mnum"))
  } %>%
  mutate(
    cumyoy_imports_pct = if_else(
      is.na(cum_imports_prev) | cum_imports_prev == 0,
      NA_real_,
      100 * (cum_imports / cum_imports_prev - 1)
    )
  )

#Prepare 2024 full-year and 2025 YTD series
series_2024 <- group7_cumyoy_all %>%
  filter(year == 2024)

series_2025 <- group7_cumyoy_all %>%
  filter(year == 2025, date <= as.Date("2025-07-01")) %>%
  # YTD up to latest available month in 2025
  filter(date <= max(date, na.rm = TRUE))

#Standardizing axes
#Find common y-axis range across both series
ymin <- min(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)
ymax <- max(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)

# Add a little padding so lines don't sit on the axis
ymin <- floor(ymin - 1)
ymax <- ceiling(ymax + 1)

#Saving data to Excel
write_xlsx(series_2025, "Figure6_HIC_data.xlsx")

#Plot builders
hic_2025 <- ggplot(series_2025, aes(x = date, y = cumyoy_imports_pct)) +
  geom_line(linewidth = 1.2, color = "#006970") +
  geom_point(size = 2.2, color = "#006970") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray40") +
  scale_x_date(
    breaks = seq(as.Date("2025-01-01"), max(series_2025$date, na.rm = TRUE), by = "1 month"),
    labels = label_date("%b"),
    limits = c(as.Date("2025-01-01"), max(series_2025$date, na.rm = TRUE))
  ) +
  scale_y_continuous(
    limits = c(-10, 40),
    labels = label_number(accuracy = 0.1, suffix = "%"),
    minor_breaks = NULL
  ) +
  labs(
    title = "High Income",
    x = NULL,
    y = "Cumulative YoY %"
  ) +
  theme_minimal(base_family = "Sofia Pro") +
  theme(
    # Title
    plot.title   = element_text(family = "Sofia Pro", face = "bold", size = 18, hjust = 0.5),
    
    # Axes
    axis.title   = element_text(family = "Sofia Pro Medium", size = 12),
    
    # Grid
    panel.grid.minor = element_blank(),
    
    # Legend
    legend.position = "none"
  ) + 
  theme(aspect.ratio = 1.2)


###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
#Graph 2: LMICs
month_levels <- c("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC")

group7_monthly_all <- census %>%
  mutate(year = as.numeric(as.character(year))) %>%
  filter(CTYNAME %in% lmic_countries, year %in% 2023:2025) %>%
  select(year, CTYNAME, matches("^[IE][A-Z]{3}$")) %>%
  pivot_longer(
    -c(year, CTYNAME),
    names_to   = c("flow","mon"),
    names_pattern = "^([IE])([A-Z]{3})$",
    values_to  = "value"
  ) %>%
  mutate(
    flow = if_else(flow == "I", "imports", "exports"),
    mon  = factor(mon, levels = month_levels),
    mnum = as.integer(mon),
    date = as.Date(sprintf("%04d-%02d-01", year, mnum)),
    value = as.numeric(value)
  ) %>%
  filter(flow == "imports") %>%
  group_by(year, mnum, date) %>%
  summarise(imports = sum(value, na.rm = TRUE), .groups = "drop") %>%
  arrange(date)

#Helper: compute cumulative YoY (YTD) for imports for all years in table
group7_cumyoy_all <- group7_monthly_all %>%
  group_by(year) %>%
  arrange(mnum, .by_group = TRUE) %>%
  mutate(cum_imports = cumsum(imports)) %>%
  ungroup() %>%
  select(year, mnum, date, cum_imports) %>%
  {
    df <- .
    prior <- df %>%
      transmute(
        year = year + 1L,          # align prior-year YTD to current year
        mnum,
        cum_imports_prev = cum_imports
      )
    left_join(df, prior, by = c("year","mnum"))
  } %>%
  mutate(
    cumyoy_imports_pct = if_else(
      is.na(cum_imports_prev) | cum_imports_prev == 0,
      NA_real_,
      100 * (cum_imports / cum_imports_prev - 1)
    )
  )

#Prepare 2024 full-year and 2025 YTD series
series_2024 <- group7_cumyoy_all %>%
  filter(year == 2024)

series_2025 <- group7_cumyoy_all %>%
  filter(year == 2025, date <= as.Date("2025-07-01")) %>%
  # YTD up to latest available month in 2025
  filter(date <= max(date, na.rm = TRUE))

#Standardizing axes
#Find common y-axis range across both series
ymin <- min(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)
ymax <- max(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)

# Add a little padding so lines don't sit on the axis
ymin <- floor(ymin - 1)
ymax <- ceiling(ymax + 1)



#Saving data to Excel
write_xlsx(series_2025, "Figure6_LMIC_data.xlsx")


#Plot builders
lmic_2025 <- ggplot(series_2025, aes(x = date, y = cumyoy_imports_pct)) +
  geom_line(linewidth = 1.2, color = "#006970") +         # teal line
  geom_point(size = 2.2, color = "#006970") +             # teal points
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray40") +
  scale_x_date(
    breaks = seq(as.Date("2025-01-01"),
                 max(series_2025$date, na.rm = TRUE),
                 by = "1 month"),
    labels = label_date("%b"),
    limits = c(as.Date("2025-01-01"), max(series_2025$date, na.rm = TRUE))
  ) +
  scale_y_continuous(
    limits = c(-10, 40),
    labels = label_number(accuracy = 0.1, suffix = "%"),
    minor_breaks = NULL
  ) +
  labs(
    title = "Lower-Middle Income",
    x = NULL,
    y = "Cumulative YoY %"
  ) +
  theme_minimal(base_family = "Sofia Pro") +
  theme(
    #Titles
    plot.title    = element_text(family = "Sofia Pro", face = "bold", size = 18, hjust = 0.5),
    plot.caption  = element_text(family = "Sofia Pro Medium", size = 10, hjust = 0.5),
    
    #Axes
    axis.title    = element_text(family = "Sofia Pro Medium", size = 12),
    
    #Grid
    panel.grid.minor = element_blank(),
    
    #Legend
    legend.position = "none"
  ) + 
  theme(aspect.ratio = 1.2)








###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
#Graph 3: UMICs
month_levels <- c("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC")

group7_monthly_all <- census %>%
  mutate(year = as.numeric(as.character(year))) %>%
  filter(CTYNAME %in% umic_countries, year %in% 2023:2025) %>%
  select(year, CTYNAME, matches("^[IE][A-Z]{3}$")) %>%
  pivot_longer(
    -c(year, CTYNAME),
    names_to   = c("flow","mon"),
    names_pattern = "^([IE])([A-Z]{3})$",
    values_to  = "value"
  ) %>%
  mutate(
    flow = if_else(flow == "I", "imports", "exports"),
    mon  = factor(mon, levels = month_levels),
    mnum = as.integer(mon),
    date = as.Date(sprintf("%04d-%02d-01", year, mnum)),
    value = as.numeric(value)
  ) %>%
  filter(flow == "imports") %>%
  group_by(year, mnum, date) %>%
  summarise(imports = sum(value, na.rm = TRUE), .groups = "drop") %>%
  arrange(date)

#Helper: compute cumulative YoY (YTD) for imports for all years in table
group7_cumyoy_all <- group7_monthly_all %>%
  group_by(year) %>%
  arrange(mnum, .by_group = TRUE) %>%
  mutate(cum_imports = cumsum(imports)) %>%
  ungroup() %>%
  select(year, mnum, date, cum_imports) %>%
  {
    df <- .
    prior <- df %>%
      transmute(
        year = year + 1L,          # align prior-year YTD to current year
        mnum,
        cum_imports_prev = cum_imports
      )
    left_join(df, prior, by = c("year","mnum"))
  } %>%
  mutate(
    cumyoy_imports_pct = if_else(
      is.na(cum_imports_prev) | cum_imports_prev == 0,
      NA_real_,
      100 * (cum_imports / cum_imports_prev - 1)
    )
  )

#Prepare 2024 full-year and 2025 YTD series
series_2024 <- group7_cumyoy_all %>%
  filter(year == 2024)

series_2025 <- group7_cumyoy_all %>%
  filter(year == 2025, date <= as.Date("2025-07-01")) %>%
  # YTD up to latest available month in 2025
  filter(date <= max(date, na.rm = TRUE))

#Standardizing axes
#Find common y-axis range across both series
ymin <- min(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)
ymax <- max(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)

# Add a little padding so lines don't sit on the axis
ymin <- floor(ymin - 1)
ymax <- ceiling(ymax + 1)

#Saving data to Excel
write_xlsx(series_2025, "Figure6_UMIC_data.xlsx")

#Plot builder
umic_2025 <- ggplot(series_2025, aes(x = date, y = cumyoy_imports_pct)) +
  geom_line(linewidth = 1.2, color = "#006970") +         # teal line
  geom_point(size = 2.2, color = "#006970") +             # teal points
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray40") +
  scale_x_date(
    breaks = seq(as.Date("2025-01-01"),
                 max(series_2025$date, na.rm = TRUE),
                 by = "1 month"),
    labels = label_date("%b"),
    limits = c(as.Date("2025-01-01"), max(series_2025$date, na.rm = TRUE))
  ) +
  scale_y_continuous(
    limits = c(-10, 40),
    labels = label_number(accuracy = 0.1, suffix = "%"),
    minor_breaks = NULL
  ) +
  labs(
    title    = "Upper-Middle Income",
 #   subtitle = "Excluding China",
    x = NULL,
    y = "Cumulative YoY %"
  ) +
  theme_minimal(base_family = "Sofia Pro") +
  theme(
    # Titles
    plot.title    = element_text(family = "Sofia Pro", face = "bold",   size = 18, hjust = 0.5),
    plot.subtitle = element_text(family = "Sofia Pro", face = "italic", size = 14, hjust = 0.5),
    plot.caption  = element_text(family = "Sofia Pro Medium", size = 10, hjust = 0.5),
    
    # Axes
    axis.title    = element_text(family = "Sofia Pro Medium", size = 12),
    
    # Grid
    panel.grid.minor = element_blank(),
    
    # Legend
    legend.position = "none"
  ) + 
  theme(aspect.ratio = 1.2)









###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
###########
#Graph 4: LICs
month_levels <- c("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC")

group7_monthly_all <- census %>%
  mutate(year = as.numeric(as.character(year))) %>%
  filter(CTYNAME %in% lic_countries, year %in% 2023:2025) %>%
  select(year, CTYNAME, matches("^[IE][A-Z]{3}$")) %>%
  pivot_longer(
    -c(year, CTYNAME),
    names_to   = c("flow","mon"),
    names_pattern = "^([IE])([A-Z]{3})$",
    values_to  = "value"
  ) %>%
  mutate(
    flow = if_else(flow == "I", "imports", "exports"),
    mon  = factor(mon, levels = month_levels),
    mnum = as.integer(mon),
    date = as.Date(sprintf("%04d-%02d-01", year, mnum)),
    value = as.numeric(value)
  ) %>%
  filter(flow == "imports") %>%
  group_by(year, mnum, date) %>%
  summarise(imports = sum(value, na.rm = TRUE), .groups = "drop") %>%
  arrange(date)

#Helper: compute cumulative YoY (YTD) for imports for all years in table
group7_cumyoy_all <- group7_monthly_all %>%
  group_by(year) %>%
  arrange(mnum, .by_group = TRUE) %>%
  mutate(cum_imports = cumsum(imports)) %>%
  ungroup() %>%
  select(year, mnum, date, cum_imports) %>%
  {
    df <- .
    prior <- df %>%
      transmute(
        year = year + 1L,          # align prior-year YTD to current year
        mnum,
        cum_imports_prev = cum_imports
      )
    left_join(df, prior, by = c("year","mnum"))
  } %>%
  mutate(
    cumyoy_imports_pct = if_else(
      is.na(cum_imports_prev) | cum_imports_prev == 0,
      NA_real_,
      100 * (cum_imports / cum_imports_prev - 1)
    )
  )

#Prepare 2024 full-year and 2025 YTD series
series_2024 <- group7_cumyoy_all %>%
  filter(year == 2024)

series_2025 <- group7_cumyoy_all %>%
  filter(year == 2025, date <= as.Date("2025-07-01")) %>%
  # YTD up to latest available month in 2025
  filter(date <= max(date, na.rm = TRUE))

#Standardizing axes
#Find common y-axis range across both series
ymin <- min(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)
ymax <- max(c(series_2024$cumyoy_imports_pct, series_2025$cumyoy_imports_pct), na.rm = TRUE)

#Add a little padding so lines don't sit on the axis
ymin <- floor(ymin - 1)
ymax <- ceiling(ymax + 1)

#Saving data to Excel
write_xlsx(series_2025, "Figure6_LIC_data.xlsx")

#Plot builders
lic_2025 <- ggplot(series_2025, aes(x = date, y = cumyoy_imports_pct)) +
  geom_line(linewidth = 1.2, color = "#006970") +          # teal line
  geom_point(size = 2.2, color = "#006970") +              # teal points
  geom_hline(yintercept = 0, linetype = "dashed", color = "gray40") +
  scale_x_date(
    breaks = seq(as.Date("2025-01-01"),
                 max(series_2025$date, na.rm = TRUE),
                 by = "1 month"),
    labels = label_date("%b"),
    limits = c(as.Date("2025-01-01"), max(series_2025$date, na.rm = TRUE))
  ) +
  scale_y_continuous(
    limits = c(-10, 40),
    labels = label_number(accuracy = 0.1, suffix = "%"),
    minor_breaks = NULL
  ) +
  labs(
    title    = "Low Income",
    x = NULL,
    y = "Cumulative YoY %"
  ) +
  theme_minimal(base_family = "Sofia Pro") +
  theme(
    #Title block
    plot.title    = element_text(family = "Sofia Pro", face = "bold",   size = 18, hjust = 0.5),
    plot.caption  = element_text(family = "Sofia Pro Medium", size = 10, hjust = 0.5),
    
    #Axes
    axis.title    = element_text(family = "Sofia Pro Medium", size = 12),
    
    #Grid
    panel.grid.minor = element_blank(),
    
    #Legend
    legend.position = "none"
  ) + 
  theme(aspect.ratio = 1.2)



#### FIGURE 6 COMBO

combined_plot <-   (hic_2025 + umic_2025) /
  (lmic_2025 + lic_2025) 

combined_plot +
  plot_annotation(
    title = "Figure 6: Cumulative YoY% Year to Date Imports by Income Group",
    caption = "Source: U.S. Census Bureau",
    subtitle = "Cumulative year-to-date change in U.S. imports, Jan – July 2025",
    theme = theme(
      plot.title    = element_text(family = "Sofia Pro", face = "bold", size = 22, hjust = 0.5),
      plot.subtitle = element_text(family = "Sofia Pro", face = "italic", size = 14, hjust = 0.5),
      plot.caption  = element_text(family = "Sofia Pro Medium", size = 10, hjust = 0.5),
      aspect.ratio  = 1.5
    )
  )


combined_plot_2 <-   (hic_2025 + umic_2025 + lmic_2025 + lic_2025) 
combined_plot_2 +
  plot_annotation(
    title = "Figure 6: Cumulative YoY% Year to Date Imports by Income Group",
    caption = "Source: U.S. Census Bureau",
    subtitle = "Cumulative year-to-date change in U.S. imports, Jan – July 2025",
    theme = theme(
      plot.title    = element_text(family = "Sofia Pro", face = "bold", size = 22, hjust = 0.5),
      plot.subtitle = element_text(family = "Sofia Pro", face = "italic", size = 14, hjust = 0.5),
      plot.caption  = element_text(family = "Sofia Pro Medium", size = 10, hjust = 0.5),
      aspect.ratio  = 1.5
    )
  )

