# Select four countries with different development levels
selected_countries <- c("Denmark", "United States", "Brazil", "Nigeria")
# Function to create correlation plot for a single country using ggplot2
create_country_corrplot_ggplot <- function(country_name) {
country_data <- wgi_sample %>%
filter(country == country_name) %>%
select(va, ps, ge, rq, rl, cc) %>%
filter(complete.cases(.))
if(nrow(country_data) > 5) {
cor_matrix <- cor(country_data, use = "complete.obs")
# Set lower triangle to NA to show only upper triangle
cor_matrix[lower.tri(cor_matrix)] <- NA
# Convert correlation matrix to long format for ggplot
cor_df <- cor_matrix %>%
as.data.frame() %>%
rownames_to_column("var1") %>%
pivot_longer(-var1, names_to = "var2", values_to = "correlation") %>%
filter(!is.na(correlation)) %>% # Remove NA values (lower triangle)
mutate(
var1 = factor(var1, levels = c("va", "ps", "ge", "rq", "rl", "cc")),
var2 = factor(var2, levels = c("va", "ps", "ge", "rq", "rl", "cc"))
)
ggplot(cor_df, aes(x = var1, y = var2, fill = correlation)) +
geom_tile() +
geom_text(aes(label = round(correlation, 2)), size = 3) +
scale_fill_gradient2(
low = "#762a83", mid = "#f7f7f7", high = "#e08214",
midpoint = 0, limit = c(-1, 1)) +
scale_x_discrete(labels = c("VA", "PS", "GE", "RQ", "RL", "CC")) +
scale_y_discrete(labels = c("VA", "PS", "GE", "RQ", "RL", "CC")) +
labs(title = country_name, x = "", y = "", fill = "Correlation") +
theme_minimal() +
theme(
axis.text.x = element_text(angle = 45, hjust = 1),
plot.title = element_text(hjust = 0.5, size = 12),
legend.position = "none"
) +
coord_fixed()
} else {
# Return empty plot if insufficient data
ggplot() +
labs(title = paste(country_name, "(Insufficient data)")) +
theme_void()
}
}
# Create plots for each country
plots <- map(selected_countries, create_country_corrplot_ggplot)
# Arrange plots in 2x2 grid
ggarrange(plotlist = plots, ncol = 2, nrow = 2)