# Step 1: Label EU countries
eu_countries <- c(
"Austria", "Belgium", "Bulgaria", "Croatia", "Cyprus", "Czechia", "Denmark",
"Estonia", "Finland", "France", "Germany", "Greece", "Hungary", "Ireland",
"Italy", "Latvia", "Lithuania", "Luxembourg", "Malta", "Netherlands",
"Poland", "Portugal", "Romania", "Slovakia", "Slovenia", "Spain", "Sweden"
)
merged_data2$eu <- ifelse(merged_data2$Entity %in% eu_countries, 1, 0)
merged_data2$type <- ifelse(merged_data2$Entity %in% eu_countries, "EU", "Everything Else")
# Step 2: Fit interaction model
merged_data2$eu_urbanization <- merged_data2$eu * merged_data2$urb_mean
model <- lm(life_expectancy ~ urb_mean + eu + eu_urbanization, data = merged_data2)
# Step 3: Extract coefficients
b0 <- coef(model)["(Intercept)"]
b1 <- coef(model)["urb_mean"]
b2 <- coef(model)["eu"]
b3 <- coef(model)["eu_urbanization"]
# Step 4: Compute lines
x_vals <- c(0, 100)
non_eu_line <- data.frame(
x = x_vals,
y = b0 + b1 * x_vals,
group = "Everything Else"
)
eu_line <- data.frame(
x = x_vals,
y = (b0 + b2) + (b1 + b3) * x_vals,
group = "EU"
)
regression_lines <- rbind(non_eu_line, eu_line)
# Step 5: Plot
cols <- c("Everything Else" = "black", "EU" = "blue")
shapes <- c("Everything Else" = 16, "EU" = 3)
ggplot(merged_data2) +
geom_point(data = merged_data2, aes(x = urb_mean, y = life_expectancy, color = type, shape = type), alpha = .2, size=2)+
geom_line(data = regression_lines, aes(x = x, y = y, color = group, group = group),
linetype = "solid", size = 1, alpha = .2, inherit.aes = FALSE)+
scale_shape_manual(name = "", values = shapes) +
scale_color_manual(name = "", values = cols) +
scale_x_continuous(name = "Urbanization", breaks = seq(0, 100, 20), limits = c(0, 100)) +
scale_y_continuous(name = "Life Expectancy", breaks = seq(0, 100, 20), limits = c(0, 100)) +
theme_bw() +
# Intercept annotations
annotate("point", x = 0, y = b0, color = "black", size = 3) +
annotate("text", x = 2, y = b0 + 2,
label = paste0("Intercept (a) = ", round(b0, 2)),
hjust = 0, color = "black", size = 5) +
annotate("point", x = 0, y = b0 + b2, color = "blue", size = 3) +
annotate("text", x = 2, y = b0 + b2 + 2,
label = paste0("Intercept (a) = ", round(b0 + b2, 2)),
hjust = 0, color = "blue", size = 5) +
theme(
axis.text.x = element_text(size = 14),
axis.title = element_text(size = 14),
plot.title = element_text(hjust = 0.5),
legend.position = "bottom", # Or "right", "top"
legend.title = element_blank(),
legend.box.background = element_rect(fill = 'white'),
legend.background = element_blank(),
legend.text = element_text(size = 12)
)