library(shiny)
library(plotly)
library(dplyr)
library(readxl)
library(leaflet)
library(sf)
library(htmlwidgets)
library(maps)
library(countrycode)
library(rnaturalearth)
library(rnaturalearthhires)
library(rgeoboundaries)
library(ggplot2)
library(gridExtra)
library(tidyr)
library(janitor)
library(tidyverse)
library(patchwork)
library(gridExtra) 


# Load the data
happiness_data <- read_xlsx("C:/Users/rickb/OneDrive/Richard/UVA/Stat-3280/Final Project/Happiness country rating.xlsx")
religion_data <- read_xlsx("C:/Users/rickb/OneDrive/Richard/UVA/Stat-3280/Final Project/Religious_Composition_by_Country_2010-2050.xlsx")
colonies_data <- read_xlsx("C:/Users/rickb/OneDrive/Richard/UVA/Stat-3280/Final Project/colonies.xlsx")
# Inspect the data
# head(happiness_data)


# colnames(happiness_data) <- c(
#   "Country name", "Ladder_score", "Upper whisker", "Lower whisker",
#   "Log_GDP_per_capita", "Social_support", "Healthy_life_expectancy",
#   "Freedom_to_make_life_choices", "Generosity", "Perceptions_of_corruption",
#   "Dystopia_residual"
# )

# Rename columns to match the variable names
colnames(happiness_data) <- c(
  "Country_name", "Ladder_score", "Upper_whisker", "Lower_whisker",
  "Log_GDP_per_capita", "Social_support", "Healthy_life_expectancy",
  "Freedom_to_make_life_choices", "Generosity", "Perceptions_of_corruption",
  "Dystopia_residual"
)

# Rename columns to match the variable names
colnames(colonies_data) <- c(
  "Country_name", "Experienced_Colonialism", "Retained_Cultural_Ethnic_Identity"
)
# Check column names
colnames(happiness_data)
##  [1] "Country_name"                 "Ladder_score"                
##  [3] "Upper_whisker"                "Lower_whisker"               
##  [5] "Log_GDP_per_capita"           "Social_support"              
##  [7] "Healthy_life_expectancy"      "Freedom_to_make_life_choices"
##  [9] "Generosity"                   "Perceptions_of_corruption"   
## [11] "Dystopia_residual"

When we watch the news today, it feels as though we are tuning into a symphony of sorrow-a relentless stream of pain, anguish, trials, and tribulations. The headlines scream of division, conflict, and despair. Yet, in the quiet moments of reflection, I find myself dreaming of a different world-a world illuminated by joy, one where we come together not in competition but in unity. A world where our collective mission is to uplift one another, to build communities that empower rather than oppress, and to leave the Earth better than how we found it. This vision is not a utopian fantasy; it is a goal within our reach. But it requires a redefinition of our priorities and a recalibration of our systems. At the heart of this transformation lies a simple yet profound concept: well-being.

If we wish to chart a path toward global well-being, where do we begin? Perhaps it starts with a map, not one that marks borders or territories but one that illuminates the soul of humanity. This map exists, not in parchment and ink, but in the pages of the World Happiness Report 2024. Like a compass guiding us through the complex terrain of human emotion, this report unfolds the intricacies of joy and sorrow, offering a lens through which we can understand the areas most in need of nurturing. The report is not merely a collection of data; it is a reflection of humanity’s collective heartbeat. It delves into the rhythms of happiness across generations, from the carefree laughter of youth to the quiet contentment of old age. It tells of how life’s trials and triumphs vary by region, how a child in Eastern Europe may face a brighter dawn than their counterpart in North America, where youth happiness wanes.

# Check for NA or blank column names
colnames(happiness_data)[is.na(colnames(happiness_data)) | colnames(happiness_data) == ""]
## character(0)
# Replace NA or blank column names with placeholder names
colnames(happiness_data)[is.na(colnames(happiness_data)) | colnames(happiness_data) == ""] <- paste0("V", seq_len(sum(is.na(colnames(happiness_data)) | colnames(happiness_data) == "")))

# Verify columns before generating ISO3 codes
unique(happiness_data$Country_name[is.na(happiness_data$Country_name) | happiness_data$Country_name == ""])
## character(0)
# Add ISO3 country codes to happiness data
happiness_data <- happiness_data %>%
  mutate(iso3c = countrycode(Country_name, 'country.name', 'iso3c'))

# Load world spatial data
world_data <- ne_countries(scale = "medium", returnclass = "sf")

# Add ISO3 codes to spatial data
world_data <- world_data %>%
  mutate(iso3c = countrycode(name_long, 'country.name', 'iso3c'))

# Create a named vector for corrections
corrections <- c(
  "Taiwan Province of China" = "Taiwan",
  "Hong Kong S.A.R. of China" = "Hong Kong",
  "Congo (Brazzaville)" = "Republic of the Congo",
  "Congo (Kinshasa)" = "Democratic Republic of the Congo",
  "Ivory Coast" = "Côte d'Ivoire",
  "Eswatini" = "Swaziland",
  "Turkiye" = "Turkey",
  "Russia" = "Russian Federation",
  "State of Palestine" = "Palestine",
  "South Korea" = "Korea, South",
  "North Macedonia" = "Macedonia",
  "Vietnam" = "Viet Nam",
  "Kosovo" = "Kosovo"
)

# Apply the corrections to the 'Country_name' column
happiness_data <- happiness_data %>%
  mutate(
    Country_name = ifelse(
      Country_name %in% names(corrections),
      corrections[Country_name],
      Country_name
    ),
    iso3c = countrycode(Country_name, "country.name", "iso3c")
  )

# Handle Kosovo manually
happiness_data <- happiness_data %>%
  mutate(iso3c = ifelse(Country_name == "Kosovo", "XKX", iso3c))

# Load world spatial data
world_sf <- ne_countries(scale = "medium", returnclass = "sf")

# Add ISO3 codes to spatial data
world_sf <- world_sf %>%
  mutate(iso3c = countrycode(name_long, "country.name", "iso3c"))

# Obtain Kosovo's spatial data
kosovo_sf <- geoboundaries(country = "Kosovo", adm_lvl = 0) %>%
  mutate(
    name_long = "Kosovo",
    iso_a3 = "XKX",
    iso3c = "XKX"
  )

# Ensure consistent column names between world_data and world_sf
common_columns <- intersect(names(world_data), names(world_sf))
world_data <- world_data[, common_columns, drop = FALSE]
world_sf <- world_sf[, common_columns, drop = FALSE]

# Combine the two data frames
combined_data <- rbind(world_data, world_sf)

# # Check for missing iso3c codes
# missing_iso3c <- happiness_data %>%
#   filter(is.na(iso3c)) %>%
#   select(Country_name)
# #print("Missing ISO3C Codes:")
# #print(missing_iso3c)

# Merge happiness data with spatial data
happiness_sf <- world_sf %>%
  left_join(happiness_data, by = "iso3c")

# Create color palette with grey for countries with no data
palette <- colorNumeric(
  palette = "YlOrRd",
  domain = happiness_sf$`Ladder_score`,
  na.color = "grey"
)

# Create the interactive map
leaflet(happiness_sf) %>%
  addTiles() %>%
  addPolygons(
    fillColor = ~palette(`Ladder_score`),
    fillOpacity = 0.8,
    color = "black",
    weight = 0.5,
    popup = ~paste(
      "<strong>Country:</strong>", name_long, "<br>",
      "<strong>Ladder_score:</strong>", `Ladder_score`, "<br>",
      "<strong>GDP Contribution:</strong>", `Log_GDP_per_capita`
    ),
    label = ~name_long
  ) %>%
  addLegend(
    pal = palette,
    values = ~`Ladder_score`,
    title = "Happiness Score",
    position = "bottomright"
  )

Paints a vivid picture of the global happiness levels. The map serves as a powerful visual representation, illustrating significant disparities in happiness across nations. While regions such as Europe, North America, and parts of Oceania dominate the higher end of the happiness spectrum, many countries with colonial histories face persistent challenges, particularly in Africa, South Asia, and parts of the Americas.

The distribution of happiness scores reveals a striking dichotomy among countries impacted by European colonialism. Former colonial powers in Western Europe, benefiting from centuries of economic exploitation and institutional development, often boast high levels of happiness. These nations have historically leveraged their economic and political stability to build systems that support well-being. In contrast, countries that were colonized and later regained independence frequently occupy the lower end of the spectrum. These nations have grappled with post-independence struggles such as economic rebuilding, institutional reform, and societal fragmentation, exacerbated by the lasting effects of external dependencies imposed during colonial rule.

For those nations that retained their cultural and ethnic identities post-independence, challenges appear even more pronounced. Their struggles are compounded by global systems that often marginalize non-Western cultural frameworks, leaving them to contend with undervalued traditions and external pressures to conform to Western standards of development.

Despite these overarching patterns, some post-colonial nations defy the odds and achieve relatively high levels of happiness. These exceptions, often in Asia and Latin America, demonstrate that contemporary factors such as effective governance, robust social cohesion, and economic diversification can mitigate the impacts of historical injustices. For instance, countries with strong social support systems or those that have successfully integrated their economies into global markets have shown remarkable progress. Conversely, even some historically advantaged nations grapple with challenges such as inequality, social isolation, and mental health crises, revealing that economic wealth alone cannot guarantee happiness.

This visualization underscores the need for nuanced approaches to addressing happiness disparities. Historical injustices, such as those stemming from colonialism, have left indelible marks on nations’ development trajectories. Closing these gaps requires targeted strategies that prioritize equitable growth, social cohesion, and the preservation of cultural identity. Acknowledging historical grievances while fostering inclusive policies can help nations navigate the complexities of their pasts to build brighter futures.

Ultimately, the map invites deeper reflection on global well-being. It challenges policymakers, researchers, and societies at large to address systemic inequities while recognizing that happiness is not solely a measure of wealth or history. Instead, it is shaped by a web of interconnected factors—past, present, and future—that demand holistic, empathetic, and context-sensitive solutions to ensure a more equitable and content world.

# Rename columns to match
colnames(colonies_data) <- c("Country_name", "Experienced_Colonialism", "Retained_Cultural_Ethnic_Identity")

# Merge datasets
merged_data <- happiness_data %>%
  inner_join(colonies_data, by = "Country_name")

# Create a new column for Colonial Retention
merged_data <- merged_data %>%
  mutate(
    Colonial_Retention = case_when(
      Experienced_Colonialism == TRUE & Retained_Cultural_Ethnic_Identity == TRUE ~ "Colonized & Retained Identity",
      Experienced_Colonialism == TRUE & Retained_Cultural_Ethnic_Identity == FALSE ~ "Colonized & Did Not Retain Identity",
      Experienced_Colonialism == FALSE ~ "Not Colonized"
    )
  )

# Plot the data
ggplot(merged_data, aes(x = reorder(Country_name, -Ladder_score), y = Ladder_score, fill = Colonial_Retention)) +
  geom_bar(stat = "identity", position = "dodge", color = "black") +
  labs(
    title = "Happiness Scores by Colonialism and Cultural/Ethnic Retention",
    x = "Country",
    y = "Happiness Score",
    fill = "Colonial & Retention Status"
  ) +
  theme_minimal() +
  theme(
    axis.text.x = element_text(size = 4, angle = 45, hjust = 1),
    axis.text.y = element_text(size = 10),
    axis.title.x = element_text(size = 12),
    axis.title.y = element_text(size = 12),
    legend.position = "top"
  )

# # Check column names in both datasets
# dput(colnames(happiness_data))
# dput(colnames(colonies_data))
# 
# happiness_data <- happiness_data %>% clean_names()
# colonies_data <- colonies_data %>% clean_names()
# 
# colnames(happiness_data)
# colnames(colonies_data)
# unique(happiness_data$country)
# unique(colonies_data$country)
# 
# str(merged_data)
# 

# 
# # Verify the results
# print(table(merged_data$Colonial_Retention))
# 
# # UI
# ui <- fluidPage(
#   titlePanel("Happiness and Colonial Retention"),
#   sidebarLayout(
#     sidebarPanel(
#       h4("Filter Options"),
#       selectInput("retention_filter", "Colonial Retention Status:",
#                   choices = c("All", unique(merged_data$Colonial_Retention)), selected = "All")
#     ),
#     mainPanel(
#       plotOutput("happinessPlot"),
#       br(),
#       p("The graph shows happiness scores (bars) and dystopia residuals (points) for countries. The x-axis is labeled with country names, which are angled for readability.")
#     )
#   )
# )
# 
# # Server
# server <- function(input, output) {
#   
#   filtered_data <- reactive({
#     if (input$retention_filter == "All") {
#       merged_data
#     } else {
#       merged_data %>% filter(Colonial_Retention == input$retention_filter)
#     }
#   })
#   
#   output$happinessPlot <- renderPlot({
#     ggplot(merged_data, aes(x = reorder(country, ladder_score), y = ladder_score, fill = colonial_retention)) +
#   geom_bar(stat = "identity", position = "dodge", color = "black") +
#   labs(
#     title = "Happiness Scores by Country and Colonial Experience",
#     x = "Country",
#     y = "Happiness Score",
#     fill = "Colonial Experience"
#   ) +
#   theme_minimal() +
#   theme(
#     axis.text.x = element_text(angle = 45, hjust = 1, size = 8),
#     plot.title = element_text(hjust = 0.5, size = 14)
#   ) +
#   coord_flip()
#   })
# }
# 
# # Run the app
# shinyApp(ui, server)

This bar chart presents happiness scores for various countries, grouped by their colonial history and the retention of cultural or ethnic identity. Each bar represents a country, and the colors distinguish three categories: “Colonized & Did Not Retain Identity” (red), “Colonized & Retained Identity” (green), and “Not Colonized” (blue). Countries are ordered from left to right based on their happiness scores, from the highest to the lowest.

The graph demonstrates the intricate relationship between historical colonial experiences and current happiness levels. The blue bars, representing countries that were not colonized, tend to cluster towards the higher end of the happiness spectrum, suggesting a potential link between historical sovereignty and higher happiness scores. These countries may have experienced fewer disruptions to their social, cultural, and political systems, which could have fostered stability and well-being.

In contrast, the green bars, which denote countries that were colonized but retained their cultural or ethnic identity, are more evenly distributed across the happiness scale. This suggests that while colonialism might have disrupted these countries’ histories, the retention of cultural identity may have served as a buffer, preserving social cohesion and providing a foundation for recovery and well-being.

The red bars, representing countries that were colonized and did not retain their cultural or ethnic identity, show a concerning trend toward lower happiness scores. This indicates that losing cultural identity due to colonial influence might have led to a weaker sense of national identity, societal cohesion, or autonomy, potentially contributing to lower happiness levels.

The visualization underscores the long-term impact of historical events like colonialism on contemporary well-being. It also highlights the importance of cultural identity in shaping societal happiness. While economic and social factors undoubtedly play a role, this chart suggests that historical sovereignty and cultural continuity remain critical to understanding global variations in happiness.

# Replace missing values (if any) with 0
happiness_data[is.na(happiness_data)] <- 0

happiness_data <- happiness_data %>% clean_names()

# Calculate the sum of explanatory variables
explanatory_totals <- colSums(happiness_data[, c(
  "social_support", "healthy_life_expectancy", "log_gdp_per_capita",
  "freedom_to_make_life_choices", "generosity",
  "perceptions_of_corruption", "dystopia_residual"
)])

# Calculate percentages
explanatory_percentages <- explanatory_totals / sum(explanatory_totals) * 100

# Prepare a data frame for the pie chart
pie_data <- data.frame(
  Variable = names(explanatory_totals),  # Simplify labels
  Percentage = explanatory_percentages
)

# Plot the pie chart using ggplot2
library(ggplot2)
ggplot(pie_data, aes(x = "", y = Percentage, fill = Variable)) +
  geom_bar(stat = "identity", width = 1, color = "black") +
  coord_polar("y", start = 0) +
  labs(title = "Percentage Contribution of Explanatory Variables to Happiness", y = NULL, x = NULL) +
  theme_minimal() +
  theme(
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    panel.grid = element_blank(),
    legend.title = element_blank()
  )

Now we can see how the variables interact with the overall happiness calculation. GDP per capita, social support, and dystopia + residuals emerge as the dominant factors in shaping happiness scores across countries. It becomes evident that countries with a strong economic base, robust community networks, and minimal unexplained deficits in happiness score at the high end of the spectrum. Conversely, countries that have lost significant GDP-driving forces, often due to historical events like colonial exploitation and its aftermath, consistently fall on the lower end of the happiness scale.

This visualization reveals a troubling reality: countries that regained their independence, particularly from colonial rule, often appear to have been economically “punished” in the process. Many of these nations have struggled to rebuild their economies, with some facing decades or even centuries of stagnation or instability. The global economic system, which tends to favor wealth accumulation and perpetuation, often leaves these countries disadvantaged. In a world where “money makes money,” nations with longstanding economic dominance—backed by centuries of wealth concentration—continue to hold the upper hand. For many former colonies, this creates a structural barrier to achieving similar levels of prosperity and, by extension, happiness.

It’s striking to note how these variables interact differently for each country, reflecting complex socio-political and historical contexts. While GDP and health outcomes significantly bolster happiness in some nations, others rely more heavily on social support or perceptions of freedom. At the same time, dystopia + residuals, representing unexplained happiness, serve as a stark reminder of how subjective and nuanced the concept of well-being is. To delve deeper into these dynamics, we must further investigate how each variable interacts with specific countries to uncover hidden patterns and inequalities in the global happiness landscape.

# Rename columns to match the variable names
colnames(happiness_data) <- c(
  "Country_name", "Ladder_score", "Upper_whisker", "Lower_whisker",
  "Log_GDP_per_capita", "Social_support", "Healthy_life_expectancy",
  "Freedom_to_make_life_choices", "Generosity", "Perceptions_of_corruption",
  "Dystopia_residual"
)

# Variables of interest
variables <- c(
  "Log_GDP_per_capita", "Social_support", "Healthy_life_expectancy",
  "Freedom_to_make_life_choices", "Generosity", "Perceptions_of_corruption",
  "Dystopia_residual"
)

# Check if all variables exist in happiness_data
missing_vars <- variables[!variables %in% colnames(happiness_data)]
if(length(missing_vars) > 0) {
  stop("The following variables are missing from happiness_data: ", paste(missing_vars, collapse = ", "))
}

# Subset the data to the variables of interest
selected_vars <- happiness_data[variables]

# Calculate the number of missing values in each variable
missing_counts <- sapply(selected_vars, function(x) sum(is.na(x)))
# print(missing_counts)

# Remove rows with missing values
rows_to_keep <- apply(selected_vars, 1, function(row) all(!is.na(row)))
happiness_data_clean <- happiness_data[rows_to_keep, ]

# Reshape data to long format
happiness_long <- do.call(rbind, lapply(variables, function(var) {
  data.frame(
    Country_name = happiness_data_clean$Country_name,
    Variable = var,
    Value = happiness_data_clean[[var]]
  )
}))

# # Check for duplicates
# dup_counts <- aggregate(Value ~ Country_name + Variable, data = happiness_long, FUN = length)
# duplicates <- dup_counts[dup_counts$Value > 1, ]
# if(nrow(duplicates) > 0) {
#   print("Duplicates found:")
#   print(duplicates)
# } else {
#   print("No duplicates found.")
# }

# Check for missing values in the 'Value' column
missing_values <- sum(is.na(happiness_long$Value))
# print(paste("Total missing values in 'Value':", missing_values))

# Aggregate to remove duplicates (if any)
happiness_long <- aggregate(Value ~ Country_name + Variable, data = happiness_long, FUN = sum)

# Reorder Country_name based on the total Value
total_values <- aggregate(Value ~ Country_name, data = happiness_long, FUN = sum)

# Merge total_values back into happiness_long
happiness_long <- merge(
  happiness_long,
  total_values,
  by = "Country_name",
  suffixes = c("", "_total")
)

# Reorder Country_name factor levels based on total Value
happiness_long$Country_name <- factor(
  happiness_long$Country_name,
  levels = total_values$Country_name[order(total_values$Value, decreasing = TRUE)]
)

# Remove the extra total column if not needed
happiness_long$Value_total <- NULL

# Create the ggplot object
p <- ggplot(happiness_long, aes(
  x = Value,
  y = Country_name,
  fill = Variable,
  text = paste(
    "<b>Country:</b>", Country_name, "<br>",
    "<b>Variable:</b>", Variable, "<br>",
    "<b>Value:</b>", round(Value, 2)
  )
)) +
  geom_bar(stat = "identity", width = 0.8, color = "black") +
  labs(
    title = "Contributions to Happiness Score by Country",
    x = "Score",
    y = NULL
  ) +
  scale_fill_brewer(palette = "Set3", name = "Explanatory Variables") +
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, size = 16),
    axis.text.y = element_text(size = 8),
    axis.title.x = element_text(size = 12),
    legend.position = "top",
    legend.title = element_text(size = 12),
    legend.text = element_text(size = 10),
    panel.grid.major.x = element_blank()
  )

# Convert ggplot to plotly for interactivity
plotly_plot <- ggplotly(p, tooltip = "text")

# Display the plot
plotly_plot
# Save the plot with high resolution and larger dimensions
ggsave(
  filename = "happiness_contributions1.png",  # File name
  plot = p,                                   # ggplot object
  width = 16,                                 # Width in inches
  height = 20,                                # Height in inches
  dpi = 300,                                  # Resolution (dots per inch)
  units = "in"                                # Units for width and height
)




# # Remove rows with any NA values
# happiness_data <- happiness_data[complete.cases(happiness_data), ]
# 
# # Variables of interest
# variables <- c(
#   "Log_GDP_per_capita", "Social_support", "Healthy_life_expectancy",
#   "Freedom_to_make_life_choices", "Generosity", "Perceptions_of_corruption",
#   "Dystopia_residual"
# )
# 
# # Reshape the data into long format
# data_long <- do.call(rbind, lapply(1:nrow(happiness_data), function(i) {
#   data.frame(
#     Country_name = happiness_data$Country_name[i],
#     Variable = variables,
#     Value = as.numeric(unlist(happiness_data[i, variables]))
#   )
# }))
# 
# # Reshape data to long format
# data_long <- data.frame(
#   Variable = variables,
#   Value = as.numeric(unlist(data[variables]))
# )
# 
# # Remove rows with any NA values
# happiness_data <- happiness_data[complete.cases(happiness_data), ]
# 
# # UI
# ui <- fluidPage(
#   titlePanel("Contributions to Happiness Score by Country"),
#   sidebarLayout(
#     sidebarPanel(
#       selectInput(
#         "country", 
#         "Select a Country:", 
#         choices = c("All Countries", unique(happiness_data$Country_name)),
#         selected = "All Countries"
#       ),
#       helpText("Interactive visualization of happiness score contributions.")
#     ),
#     mainPanel(
#       plotlyOutput("plot")
#     )
#   )
# )
# 
# server <- function(input, output, session) {
#   # Subset data based on selected country
#   filtered_data <- reactive({
#     req(input$country)  # Ensure input is not NULL
#     if (input$country == "All Countries") {
#       return(happiness_data)
#     } else {
#       subset(happiness_data, Country_name == input$country)
#     }
#   })
#   
#   # Render the plot
#   output$plot <- renderPlotly({
#     filtered <- filtered_data()
#     
#     # Ensure data is available for the selected country
#     if (nrow(filtered) == 0) {
#       return(NULL)
#     }
#     
#     # Variables of interest
#     variables <- c(
#       "Log_GDP_per_capita", "Social_support", "Healthy_life_expectancy",
#       "Freedom_to_make_life_choices", "Generosity", "Perceptions_of_corruption",
#       "Dystopia_residual"
#     )
#     
#     # Reshape data to long format
#     data_long <- do.call(rbind, lapply(1:nrow(filtered), function(i) {
#       data.frame(
#         Country_name = filtered$Country_name[i],
#         Variable = variables,
#         Value = as.numeric(unlist(filtered[i, variables]))
#       )
#     }))
#     
#     # Create the plot
#     ggplot_obj <- ggplot(data_long, aes(
#       x = reorder(Variable, Value),
#       y = Value,
#       fill = Variable
#     )) +
#       geom_bar(stat = "identity", width = 0.8, color = "black") +
#       coord_flip() +
#       labs(
#         title = paste("Contributions to Happiness Score for", filtered$Country_name),
#         x = "Explanatory Variables",
#         y = "Contribution to Happiness Score",
#         fill = "Explanatory Variables"
#       ) +
#       theme_minimal() +
#       theme(
#         plot.title = element_text(hjust = 0.5, size = 16),
#         axis.text.y = element_text(size = 10),
#         axis.title.x = element_text(size = 12),
#         legend.position = "none"
#       )
#     
#     ggplotly(ggplot_obj)
#   })
# }
# # Run the app
# shinyApp(ui = ui, server = server)



# # Save the plot with high resolution and larger dimensions
# ggsave(
#   filename = "happiness_contributions1.png",  # File name
#   plot = p,                                   # ggplot object
#   width = 16,                                 # Width in inches
#   height = 20,                                # Height in inches
#   dpi = 300,                                  # Resolution (dots per inch)
#   units = "in"                                # Units for width and height
# )

This stacked bar chart vividly illustrates the interplay of multiple variables contributing to overall happiness scores across countries, arranged from the happiest nations at the top to those with lower scores at the bottom. Each colored segment of the bars represents one of seven key contributors: GDP per capita, social support, healthy life expectancy, freedom to make life choices, generosity, perceptions of corruption, and dystopia + residuals. The visualization underscores the complexities of happiness by showing how these variables interact and vary across countries with diverse economic, social, and political contexts.

At the top of the chart, countries like Finland, Denmark, and Iceland are characterized by substantial contributions from GDP per capita, represented in light green. This reflects the crucial role of economic prosperity in fostering higher happiness levels. Social support and freedom to make life choices also play significant roles in these nations, represented by blue and yellow, respectively, highlighting the importance of strong community networks and individual autonomy in promoting well-being.

As we move down the chart, the dynamics shift. Countries with lower happiness scores tend to have diminished contributions from GDP and social support, with a more noticeable reliance on “dystopia + residuals,” represented in black. This segment reflects the portion of happiness that remains unexplained by other factors. It often becomes more prominent in less happy nations, suggesting that intrinsic or unmeasured cultural and psychological elements may play a compensatory role in environments where economic and social conditions are lacking.

Additionally, perceptions of corruption, shown in red, are more pronounced in countries with lower happiness scores. This highlights how governance issues, lack of trust in institutions, and systemic inequities can significantly undermine well-being. Generosity, depicted in orange, is a smaller but important factor, varying widely across nations. It likely reflects cultural values and social systems that encourage altruistic behaviors.

Notably, this chart also reveals the long-term effects of history and governance. Many countries with a history of colonialism or prolonged political instability cluster in the middle and lower ranges of happiness. These nations often face challenges in rebuilding economic systems and fostering trust in societal structures, which are key to improving happiness. This visualization not only underscores the multifaceted nature of happiness but also highlights the critical role of equitable economic development, robust social support systems, and effective governance in shaping national well-being.

# Create individual scatter plots
plot1 <- ggplot(happiness_data, aes(x = `Log_GDP_per_capita`, y = `Ladder_score`)) +
  geom_point(color = "blue", size = 1.5) +
  labs(title = "Log GDP vs. Ladder_score", x = "Log_GDP_per_capita", y = "Happiness Score") +
  theme_minimal()
plot1

The relationship between a country’s economic prosperity and its citizens’ happiness is a cornerstone of understanding well-being on a global scale. The graph examining Log GDP per Capita vs. Overall Happiness reveals a strong positive correlation, highlighting that nations with higher GDP per capita generally report greater happiness scores. This underscores the critical role of material wealth and economic security in shaping life satisfaction, as wealth provides access to essential resources and reduces day-to-day uncertainty. GDP per capita, representing a nation’s economic output per person, serves as a proxy for the average standard of living. Countries with higher GDP per capita often enjoy better healthcare, education, and infrastructure, alongside opportunities for personal development and leisure. These factors collectively alleviate stress and promote stability, fostering an environment conducive to happiness.

However, the relationship between economic prosperity and happiness is complex and nuanced. While GDP per capita often serves as a strong predictor of happiness, it is not a one-size-fits-all metric. Diminishing returns to happiness become evident beyond a certain income threshold, where additional wealth yields smaller increments in life satisfaction. This phenomenon is especially apparent in affluent societies where disparities such as income inequality, social isolation, or materialism undermine the potential gains from economic growth. On the other hand, some countries with modest GDP per capita achieve high happiness scores, driven by robust social networks, cultural values emphasizing community over material success, or governance that effectively prioritizes citizen welfare. These outliers challenge the traditional narrative that wealth alone defines well-being.

Ultimately, while economic prosperity is a critical foundation for happiness, it is not the sole determinant. Policymakers must acknowledge that while wealth is vital for meeting basic needs and ensuring financial security, its contribution to happiness diminishes without parallel investments in social, environmental, and emotional domains. A balanced approach that integrates economic growth with efforts to strengthen social bonds, ensure equity, and foster personal fulfillment is essential for sustainable national well-being. This graph is a reminder that economic measures, while important, tell only part of the story in the pursuit of happiness.

plot4 <- ggplot(happiness_data, aes(x = `Social_support`, y = `Freedom_to_make_life_choices`)) +
  geom_point(color = "purple", size = 1.5) +
  labs(title = "Social_support vs. Freedom", x = "Social_support", y = "Freedom") +
  theme_minimal()
plot4

The interplay between Social Support and Freedom to Make Life Choices underscores the profound synergy between communal well-being and individual autonomy. The positive correlation shown in the graph reveals that societies with strong social support systems foster a greater sense of personal freedom among their citizens. This relationship highlights how the strength of communal bonds can empower individuals, creating a mutually reinforcing dynamic between societal support and personal autonomy.

Social support encompasses the networks of family, friends, and community that provide emotional, practical, and informational assistance. Acting as a safety net, it ensures that individuals are not isolated in times of need. When people feel supported by their community, they often perceive greater control over their lives, enabling them to make decisions that positively impact their well-being. This sense of autonomy is critical for personal growth, self-efficacy, and overall life satisfaction. Importantly, it suggests that the foundations of individual freedom are deeply rooted in collective solidarity.

However, the relationship between social support and freedom is not without complexity. A feedback loop emerges where strong social support directly contributes to well-being while simultaneously empowering individuals to pursue their aspirations and take meaningful risks. This empowerment fosters confidence and resilience, allowing individuals to make choices that align with their values and goals. Conversely, in societies with weaker social support systems, individuals may feel constrained by external pressures such as economic instability or social isolation, leading to a diminished sense of autonomy and life satisfaction.

This dynamic highlights the dual importance of collective and individual thriving. Communities that prioritize both social bonds and personal freedoms can create environments where people flourish in harmony. Policies that strengthen social cohesion—such as robust welfare programs, community-building initiatives, and inclusive practices—can serve as catalysts for enhancing both social support and individual autonomy. By recognizing and nurturing this interconnectedness, societies can cultivate ecosystems where people experience the best of both communal and personal well-being.

plot7 <- ggplot(happiness_data, aes(x = `Perceptions_of_corruption`, y = `Freedom_to_make_life_choices`)) +
  geom_point(color = "cyan", size = 1.5) +
  labs(title = "Corruption vs. Freedom", x = "Perceptions_of_corruption", y = "Freedom") +
  theme_minimal()
plot7

The inverse relationship between Perceptions of Corruption and Freedom to Make Life Choices illustrates the profound impact governance and institutional integrity have on individual autonomy. The graph demonstrates that as perceptions of corruption diminish, people experience a stronger sense of control over their lives and decision-making. This connection highlights the critical role that institutional trust and fairness play in fostering personal empowerment and societal well-being.

Corruption undermines trust in institutions, weakens the rule of law, and erodes confidence in merit-based systems. In societies where corruption is prevalent, individuals often feel that success is dictated by unfair practices, favoritism, or bribes rather than by merit or hard work. This perception fosters feelings of helplessness and disillusionment, stripping people of the belief that they can shape their own circumstances. Conversely, societies with low levels of corruption create environments where individuals trust that their efforts and choices can lead to meaningful outcomes, enhancing their sense of freedom and agency.

The relationship between corruption and perceived freedom is complex and multifaceted. Corruption not only limits individual opportunities but also exacerbates social inequalities and hinders access to essential services. These structural barriers restrict social mobility and disproportionately impact vulnerable populations, compounding feelings of powerlessness. Moreover, even the perception of corruption—regardless of its actual prevalence—can significantly damage societal trust, further undermining individual and collective well-being.

Addressing corruption requires systemic reforms that prioritize transparency, accountability, and good governance. Efforts to curb corruption can empower individuals by restoring faith in institutions, ensuring equal opportunities, and promoting social equity. This empowerment fosters an environment where people feel free to make meaningful choices, ultimately contributing to higher levels of happiness and societal prosperity. Recognizing the deep ties between institutional integrity and personal autonomy can guide policy efforts aimed at creating fairer, more inclusive societies.

plot2 <- ggplot(happiness_data, aes(x = `Healthy_life_expectancy`, y = `Ladder_score`)) +
  geom_point(color = "red", size = 1.5) +
  labs(title = "Life Expectancy vs. Ladder_score", x = "Healthy_life_expectancy", y = "Happiness Score") +
  theme_minimal()
plot2

Health is a cornerstone of well-being, and the relationship between Healthy Life Expectancy and Overall Happiness underscores its critical importance. The graph illustrates a strong positive correlation, showing that countries with higher healthy life expectancies consistently report higher happiness scores. This relationship highlights the fundamental role that good health plays in enabling individuals to lead fulfilling, active, and satisfying lives.

Healthy life expectancy extends beyond mere longevity; it reflects the quality of health throughout one’s lifespan. When individuals enjoy good health, they can engage in daily activities, pursue personal and professional goals, and maintain meaningful relationships without being hindered by illness or disability. Additionally, good health alleviates the financial and emotional burdens associated with healthcare costs and chronic diseases, further enhancing overall life satisfaction.

The connection between health and happiness, however, is shaped by a variety of complex factors. Access to healthcare services, lifestyle choices, environmental conditions, and genetic predispositions all influence health outcomes. Socioeconomic disparities within and between countries exacerbate inequalities in health, creating significant gaps in well-being. Moreover, mental health, a critical yet often overlooked aspect of overall health, profoundly affects happiness. Its interplay with physical health and societal factors further complicates the picture.

Investing in healthcare infrastructure, preventive medicine, and health education offers an opportunity to amplify national happiness. Such investments not only improve physical health but also address mental health and the broader social determinants of health, such as income, education, and housing. Recognizing the central role of health in fostering well-being can inform public policy and resource allocation, ensuring a more equitable and impactful approach to enhancing societal happiness. By prioritizing comprehensive healthcare and addressing disparities, nations can create environments where individuals and communities thrive.

Happiness is the result of a deeply interconnected web of factors, as highlighted by these analyses. Economic prosperity, social dynamics, governance, and health emerge as the primary influences, each interacting in complex ways to shape the well-being of nations. Rather than being dominated by a single variable, happiness reflects the interplay of multiple dimensions of human life, demonstrating the multifaceted nature of this universal pursuit.

For policymakers, these insights underscore the importance of adopting a holistic approach to national well-being. Economic growth remains a critical driver, but it must be balanced with strategic investments in social support systems, robust healthcare infrastructure, and transparent, effective governance. Reducing corruption fosters trust and empowers individuals, while promoting social cohesion enhances community support and personal autonomy. Equitable access to resources is also essential, as it ensures that prosperity and opportunity are widely shared, lifting the collective happiness of a society.

However, the complexities of happiness lie in the unique cultural, historical, and social contexts of each country. Policies that are effective in one nation may not be directly applicable to another, as societal values and traditions shape the ways in which individuals perceive and experience happiness. This necessitates a culturally sensitive approach to policy-making, one that addresses the specific challenges and builds upon the strengths of each nation.

In conclusion, fostering happiness requires a comprehensive strategy that integrates economic, social, governance, and health-related dimensions. By addressing these factors collectively, societies can create environments that offer individuals the freedom and opportunities to lead fulfilling lives. Beyond the data, the trends observed in dystopia residuals remind us that happiness also encompasses elements that cannot be fully explained by quantifiable variables. These intangibles—culture, resilience, and the human spirit—play an equally vital role in shaping a happier and more prosperous world. Exploring the disparities between nations may uncover deeper stories, helping us understand what drives happiness beyond the variables we have seen.

# Filter to ensure complete cases for Ladder Score and Dystopia Residual 
filtered_data <- happiness_data %>%
  select(Country_name, Ladder_score, Dystopia_residual) %>%
  filter(!is.na(Ladder_score) & !is.na(Dystopia_residual))

# Sort countries by Ladder Score (Descending)
sorted_data <- filtered_data %>%
  arrange(desc(Ladder_score))

# Add a unique number for each country
sorted_data <- sorted_data %>%
  mutate(Number = row_number())  # Assign unique numbers

# Define a 'Highlight' variable to color-code points for Top 15, Middle 15, and Bottom 15
n <- nrow(sorted_data)
sorted_data <- sorted_data %>%
  mutate(
    Highlight = case_when(
      Number <= 15 ~ "Top 15",  # Top 15 countries by Ladder_score
      Number > (n - 15) ~ "Bottom 15",  # Bottom 15 countries by Ladder_score
      Number > (n / 2 - 7) & Number <= (n / 2 + 7) ~ "Middle 15",  # Middle 15 countries
      TRUE ~ "Others"
    )
  )

# Create Scatterplot with Numbers
scatter_plot_with_numbers <- ggplot(sorted_data, aes(
    x = Dystopia_residual,
    y = Ladder_score,
    label = Number
  )) +
  geom_point(aes(color = Highlight), size = 3, alpha = 0.7) +
  geom_text(hjust = 0.5, vjust = -1, size = 3) +
  labs(
    title = "Relationship Between Ladder Score and Dystopia Residual",
    x = "Dystopia Residual (Unexplained Happiness)",
    y = "Ladder Score (Overall Happiness)",
    color = "Category"
  ) +
  theme_minimal() +
  theme(legend.position = "top")

# Create the Legend as a Separate Table (with improved formatting)
legend_data <- sorted_data %>%
  select(Number, Country_name, Highlight) %>%
  arrange(Number)  # Ensure the legend is sorted by number

# Use ggplot2 to make the legend more legible as a table
legend_table <- ggplot(legend_data, aes(
    x = 1, 
    y = Number, 
    label = paste0(Number, ": ", Country_name, " (", Highlight, ")")
  )) +
  geom_text(hjust = 0, size = 0.75) +  # Increased text size for legibility
  labs(title = "Legend: Country Numbers") +
  theme_void() +
  theme(
    plot.title = element_text(size = 14, hjust = 0.5, face = "bold"),
    plot.margin = margin(5, 5, 5, 5)
  )

# Display both plots together using patchwork
combined_plot <- scatter_plot_with_numbers + legend_table + plot_layout(widths = c(2, 1))

# Display the Combined Plot
print(combined_plot)

# # Prepare data for the scatter plot and legend
# sorted_data <- happiness_data %>%
#   select(Country_name, Ladder_score, Dystopia_residual) %>%
#   filter(!is.na(Ladder_score) & !is.na(Dystopia_residual)) %>%
#   arrange(desc(Dystopia_residual)) %>%
#   mutate(Number = row_number(), Highlight = ifelse(Number <= 10, "Top 10", "Others"))
# 
# # Prepare legend_data with unique numbers and country names
# legend_data <- sorted_data %>% 
#   select(Number, Country_name) %>% 
#   arrange(Number)  # Ensure the rows are ordered by Number
# 
# # Shiny UI
# ui <- fluidPage(
#   titlePanel("Relationship Between Ladder Score and Dystopia Residual"),
#   sidebarLayout(
#     sidebarPanel(
#       selectInput(
#         "category",
#         "Highlight Category:",
#         choices = c("All", "Top 10", "Others"),
#         selected = "All"
#       ),
#       checkboxInput("show_legend", "Show Legend", value = TRUE),
#       helpText("Explore the relationship between happiness scores and unexplained happiness (Dystopia Residual).")
#     ),
#     mainPanel(
#       plotOutput("scatter_plot", height = "600px"),
#       conditionalPanel(
#         condition = "input.show_legend",
#         plotOutput("legend_table", height = "400px")
#       )
#     )
#   )
# )
# 
# # Shiny Server
# server <- function(input, output, session) {
#   # Filter data based on the selected category
# filtered_data <- reactive({
#   req(input$highlight_category)
#   filtered <- sorted_data %>% filter(Highlight == input$highlight_category | input$highlight_category == "All")
#   print(filtered)  # Debug: Check filtered data
#   filtered
# })
# 
# observe({
#   print(input$highlight_category)
#   print(input$show_legend)
# })
# 
#   # Render scatter plot
# output$scatter_plot <- renderPlotly({
#   data <- filtered_data()
#   print(data)  # Debug: Check data used for plotting
#   
#   ggplot(data, aes(
#     x = Dystopia_residual,
#     y = Ladder_score,
#     label = Number
#   )) +
#     geom_point(aes(color = Highlight), size = 3, alpha = 0.7) +
#     geom_text(hjust = 0.5, vjust = -1, size = 3) +
#     labs(
#       title = "Relationship Between Ladder Score and Dystopia Residual",
#       x = "Dystopia Residual (Unexplained Happiness)",
#       y = "Ladder Score (Overall Happiness)",
#       color = "Category"
#     ) +
#     theme_minimal() +
#     theme(legend.position = "top")
# })
# 
# # Render legend table
# output$legend_table <- renderPlot({
#   if (!input$show_legend) return(NULL)
#   print(legend_data)  # Debug: Check legend data
#   
#   ggplot(legend_data, aes(
#     x = 1,
#     y = Number,
#     label = paste(Number, Country_name)
#   )) +
#     geom_text(hjust = 0, size = 3) +
#     labs(title = "Legend: Country Numbers") +
#     theme_void()
# })
# }
# # Run the Shiny App
# shinyApp(ui = ui, server = server)

This scatter plot intricately portrays the relationship between overall happiness scores (Ladder Scores) and dystopia residuals (unexplained happiness), emphasizing distinctions between the “Top 15”, “Middle 15,”Bot 15“, and the”Others" happiest countries. The x-axis, representing dystopia residuals, highlights an abstract baseline of happiness derived from unquantified factors, such as cultural or psychological elements, while the y-axis reflects overall happiness. A dense clustering of countries in the mid-range of both metrics (Ladder Scores of 4–6 and dystopia residuals of 1–2) suggests a global convergence where nations, despite differences in measurable factors like GDP or social support, share similar levels of resilience or societal stability. The “Top 10” happiest countries, such as Finland, Denmark, and Iceland, consistently achieve high Ladder Scores even with moderate dystopia residuals, illustrating that their happiness is predominantly supported by measurable conditions, such as economic prosperity and strong social systems. In contrast, countries with lower Ladder Scores (below 4) show varying reliance on dystopia residuals. While some demonstrate cultural or societal resilience compensating for tangible deficits, others with both low residuals and Ladder Scores, such as Afghanistan or Yemen, reflect compounded challenges, with systemic issues stifling both measurable and unexplained happiness contributors.

The positioning of outliers reveals unique narratives. For instance, the “Top 10” nations stand apart as a distinct group whose happiness is less reliant on unexplained factors, reflecting the significant role of measurable variables like GDP and healthy life expectancy in maintaining their elevated scores. Conversely, countries with lower scores show a broader spectrum of reliance on dystopia residuals, suggesting that in resource-deprived contexts, cultural mechanisms can mitigate, though not fully bridge, the gap. The visualization underscores disparities in global happiness, highlighting how tangible investments in economic and social infrastructure correlate with higher scores, while intangible elements, such as cultural resilience, play a crucial compensatory role in less resourced nations. The accompanying legend and numbered data points add granularity, enabling detailed comparisons and highlighting specific nations’ unique trajectories. Overall, this plot challenges us to examine the interplay between measurable and intangible factors in shaping national happiness, offering insights for policymakers to balance material investments with cultural and societal well-being initiatives.

Crafted by the hands of leading thinkers and supported by institutions such as Gallup and the UN Sustainable Development Solutions Network, the World Happiness Report is more than an analysis-it is a tapestry woven from countless lives. It dares to ask the pressing questions: How do our choices shape happiness? How do systems foster or inhibit well-being? And most importantly, how can we reimagine a world where happiness is not the privilege of the few but the inheritance of all? This year’s edition is a mosaic of insights, revealing that happiness is not static; it is a dynamic force, shaped by age, culture, history, and circumstance. It calls us to listen to the unspoken truths it unearths and to act-not as individuals scattered across the globe but as a unified humanity, striving to turn this map of happiness into a brighter reality for all.

Well-being is not a luxury or a privilege; it is a fundamental human right. It is the state of feeling whole, healthy, and valued-not just physically, but emotionally, socially, and spiritually. It is attainable for everyone, yet paradoxically, it often feels distant. Why? Because the systems we’ve built-economic, political, and social-tend to create conditions that erode well-being rather than nurture it. The pursuit of endless growth has left too many behind, creating a world where wealth is concentrated in the hands of a few while millions struggle for basic survival. How can we claim well-being in a world where some fight for abundance while others fight for scraps? Our digital age promised connection, but it often delivers isolation. True unity comes from deep, meaningful bonds, yet loneliness is becoming a global epidemic. We’ve built systems that prioritize individual achievement over collective care. The very planet that sustains us is suffering from the weight of human ambition. How can humanity thrive when our air, water, and soil-the sources of life itself-are under siege? Many feel alienated from the systems meant to protect and guide them. Corruption and power dynamics breed cynicism, creating a chasm between people and the institutions they once trusted.

Reclaiming Well-Being The pursuit of well-being must become the cornerstone of our efforts as a global society. It requires us to dismantle systems that harm and rebuild ones that heal. But what does this look like in practice? A focus on policies that ensure every person has access to healthcare, education, and opportunities for economic mobility. When the most vulnerable among us are cared for, society as a whole thrives. We must reimagine our communities-not as places where we merely coexist but as ecosystems of care. Encouraging intergenerational relationships, fostering inclusive spaces, and valuing empathy will bridge the divides that isolate us. Well-being cannot flourish on a dying planet. Addressing climate change, embracing sustainable practices, and prioritizing harmony with nature are not just environmental goals-they are existential necessities. Leaders must lead with compassion and accountability, prioritizing the collective good over personal gain. Transparency, integrity, and a commitment to equity can restore trust and inspire collective action.

The pursuit of well-being begins with a shift in perspective. It’s easy to believe that systems are too entrenched, that change is too hard. But systems are human creations, and what we build, we can also rebuild. The journey starts with small acts-choosing kindness, advocating for fairness, and cultivating joy in our own lives. These ripples of change can grow into waves, reshaping our world. When I imagine a future grounded in well-being, I see a world where the news is not dominated by sorrow but by stories of triumph and connection. I see a world where humanity doesn’t just survive-it flourishes. It starts with us. It starts with now. Together, we can create a reality where well-being isn’t just an aspiration but a way of life.