install.packages(c("readxl", "dplyr", "ggplot2"),
                 repos = "https://cloud.r-project.org")

library(readxl)
library(dplyr)
library(ggplot2)

# 读取 Excel
df_raw <- read_excel(
  "C:/Users/JUNSONG SHI/OneDrive/Data/FDI&Inequality/summary data/figures.xlsx",
  sheet = "decades_divided"
)

# 只保留有系数的行
df <- df_raw %>%
  filter(!is.na(coef)) %>%
  mutate(
    sample = as.character(sample),
    n1 = as.numeric(n1)
  )

# Panel 标题位置
panel_labels <- data.frame(
  panel_label = c(
    "Panel A: ALL",
    "Panel B: LAC",
    "Panel C: Asia",
    "Panel D: Africa",
    "Panel E: Eastern Europe and Former Soviet Union"
  ),
  y = c(-1, -6, -11, -16, -20),
  x = -2.5
)

p <- ggplot(df, aes(y = n1)) +
  
  # 0 线
  geom_vline(
    xintercept = 0,
    color = "firebrick",
    linetype = "dashed",
    linewidth = 0.8
  ) +
  
  # 95% CI 横线
  geom_segment(
    aes(x = low, xend = up, yend = n1),
    color = "gray25",
    linetype = "dashed",
    linewidth = 0.8
  ) +
  
  # CI 左端点
  geom_segment(
    aes(x = low, xend = low, y = n1 - 0.15, yend = n1 + 0.15),
    color = "gray25",
    linewidth = 0.8
  ) +
  
  # CI 右端点
  geom_segment(
    aes(x = up, xend = up, y = n1 - 0.15, yend = n1 + 0.15),
    color = "gray25",
    linewidth = 0.8
  ) +
  
  # 系数点
  geom_point(
    aes(x = coef),
    color = "#1f77b4",
    size = 3
  ) +
  
  # 右侧 sample 标签
  geom_text(
    aes(x = up + 0.07, label = sample),
    hjust = 0,
    size = 4
  ) +
  
  # Panel 标题
  geom_text(
    data = panel_labels,
    aes(x = x, y = y, label = panel_label),
    inherit.aes = FALSE,
    hjust = 0,
    size = 4.5
  ) +
  
  scale_x_continuous(
    limits = c(-2.75, 2.95),
    breaks = seq(-2.5, 2.5, 0.5)
  ) +
  
  scale_y_continuous(
    limits = c(-24.5, 0),
    breaks = NULL
  ) +
  
  labs(
    x = "Coef. and 95% CIs in different samples",
    y = NULL
  ) +
  
  theme_classic(base_size = 13) +
  theme(
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.line.y = element_blank(),
    axis.line.x = element_line(color = "black", linewidth = 0.8),
    axis.title.x = element_text(size = 13),
    plot.margin = margin(10, 30, 10, 10)
  )

p

ggsave(
  "decades_divided_coef_plot.jpg",
  plot = p,
  width = 9,
  height = 6,
  dpi = 300
)
