# HSCI 410 Lesson 6, Activity 6.4: many variables and a combined figure
# Run-along script for the narrated walkthrough. It reads the course data
# directly from the course website, so there is nothing to set up: open it
# in RStudio and run each part with Ctrl+Enter when the narration asks.

# 1. Read the briefing file and load the plotting packages
brief <- read.csv("https://heal-learn.ca/r-activities/data/cscs_brief.csv")   # course data, read from the website
brief$age_group <- factor(brief$age_group,
  levels = c("16 to 29", "30 to 44", "45 to 64", "65 and older"))   # order of the groups
nrow(brief)          # people with complete data in the 2021 wave
# install.packages(c("ggplot2", "ggExtra", "patchwork"))   # once, if R cannot find them
library(ggplot2)
library(ggExtra)     # ggMarginal(): histograms in the margins of a plot
library(patchwork)   # + and / combine ggplot2 plots into one figure

# 2. A correlation matrix, and Spearman's rank correlation
vars <- c("loneliness", "support", "depression", "anxiety", "life_sat", "age")
cor_mat <- round(cor(brief[, vars]), 2)     # Pearson correlations, rounded
cor_mat
round(cor(brief$loneliness, brief$support, method = "spearman"), 2)

# 3. The matrix as a heatmap
cor_long <- as.data.frame(as.table(cor_mat))   # one row for each pair
names(cor_long) <- c("var1", "var2", "r")
head(cor_long)
p_heat <- ggplot(cor_long, aes(x = var1, y = var2, fill = r)) +
  geom_tile(colour = "white") +              # one coloured square per pair
  geom_text(aes(label = r), size = 3) +      # the value on each square
  scale_fill_gradient2(low = "#2166AC", mid = "white", high = "#B2182B",
                       limits = c(-1, 1)) +  # blue negative, red positive
  labs(x = NULL, y = NULL, fill = "r")
p_heat

# 4. A scatterplot with marginal histograms
set.seed(2021)
p_scatter <- ggplot(brief, aes(x = support, y = loneliness)) +
  geom_jitter(height = 0.2, width = 0, alpha = 0.15) +
  geom_smooth(method = "lm", colour = "#CC0033") +
  labs(x = "Social support (1 to 7)", y = "Loneliness score (3 to 9)")
ggMarginal(p_scatter, type = "histogram")    # a histogram on each axis
head(sort(table(brief$support), decreasing = TRUE), 3)   # the tallest spikes

# 5. Four plots in one figure, saved for print
p_hist <- ggplot(brief, aes(x = loneliness)) +
  geom_histogram(binwidth = 1, fill = "#0B7B6B", colour = "white") +
  labs(x = "Loneliness score (3 to 9)", y = "Number of people")
p_box <- ggplot(brief, aes(x = age_group, y = loneliness)) +
  geom_boxplot(fill = "#E6F3F0") +
  labs(x = "Age group", y = "Loneliness score (3 to 9)")
figure <- (p_hist + p_box) / (p_scatter + p_heat) +   # + side by side, / stacked
  plot_annotation(tag_levels = "A",                     # label the panels A to D
    title = "Loneliness and social connection, CSCS 2021 (n = 3,083)")
figure
ggsave("briefing_figure.png", figure, width = 11, height = 8.5, dpi = 300)
