pacman::p_load(pacman, readr, ggplot2, RColorBrewer, gridExtra)

# Read the CSV file
Oldest_Humans_Who_Have_Ever_Lived_2022 <- read_csv("Oldest_Humans_Who_Have_Ever_Lived_2022.csv")
## Rows: 18 Columns: 4
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (3): Name, Country, Area
## dbl (1): Age (in years)
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Create the bar chart with data labels
p1 <- ggplot(Oldest_Humans_Who_Have_Ever_Lived_2022, aes(x = reorder(Name, `Age (in years)`), 
                                                   y = `Age (in years)`, fill = Country)) +
  geom_bar(stat = "identity") +
  geom_text(aes(label = `Age (in years)`), hjust = 1.5, size = 3.5) +  
  coord_flip() +  # Flip the coordinates to make it horizontal
  labs(title = "Oldest Humans Who Have Ever Lived (as of 2022)", 
       x = "Name", 
       y = "Age (in years)") +
  scale_fill_brewer(palette = "Set3") +  # Use a colour palette for countries
  theme() +
  theme(legend.title = element_text(size = 10),
        legend.text = element_text(size = 9))

# Pie Chart For Distribution

p2 <- ggplot(Oldest_Humans_Who_Have_Ever_Lived_2022, aes(x = "", fill = Country)) +
  geom_bar(width = 1) +
  coord_polar("y") +
  labs(title = "Distribution of Longest-Lived Humans by Country (as of 2022)") +
  theme_void() +
  scale_fill_brewer(palette = "Set3")
  
# Heat Map

p3 <- ggplot(Oldest_Humans_Who_Have_Ever_Lived_2022, aes(x = Area, y = Country, fill = `Age (in years)`)) +
  geom_tile() +
  labs(title = "Age vs Area Heatmap of Longest-Lived Humans (as of 2022)", 
       x = "Area", 
       y = "Country") +
  scale_fill_gradient(low = "#66ccff", high = "#000066") +
  theme() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# Histogram 

p4 <- ggplot(Oldest_Humans_Who_Have_Ever_Lived_2022, aes(x = `Age (in years)`, fill = Country)) +
  geom_histogram(binwidth = 1, position = "dodge") +
  labs(title = "Age Frequency of Longest-Lived Humans (as of 2022) by Country", 
       x = "Age (in years)", 
       y = "Count") +
  scale_fill_brewer(palette = "Set3") +
  theme()

grid.arrange(p1, p2, p3, p4, nrow = 2, ncol = 2)

print (p1)

print (p2)

print (p3)

print (p4)