# HSCI 410 Lesson 6, Activity 6.3: the grammar of graphics with ggplot2
# 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 ggplot2
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"))
brief$gender <- factor(brief$gender, levels = c("Woman", "Man", "Non-binary"))
brief$mental_health <- factor(brief$mental_health,
  levels = c("Poor", "Fair", "Good", "Very good", "Excellent"))
nrow(brief)                      # one row per person
# install.packages("ggplot2")    # once per computer, if not yet installed
library(ggplot2)

# 2. One variable: a histogram, then bars of counts and bars of values
ggplot(brief, aes(x = loneliness)) +               # data and mapping
  geom_histogram(binwidth = 1,                     # one bar per score
                 fill = "#0B7B6B", colour = "white") +   # set, not mapped
  labs(title = "Loneliness scores",
       x = "Loneliness score (3 to 9)", y = "Number of people")
ggplot(brief, aes(x = mental_health)) +
  geom_bar() +                                     # counts the rows
  labs(x = "Self-rated mental health", y = "Number of people")
means <- aggregate(loneliness ~ age_group, data = brief, FUN = mean)
means                                              # one row per age group
ggplot(means, aes(x = age_group, y = loneliness)) +
  geom_col() +                                     # draws the values given
  labs(x = "Age group", y = "Mean loneliness score")

# 3. A numeric variable across groups: boxplots with every person
set.seed(2021)                                     # the same jitter every time
ggplot(brief, aes(x = age_group, y = loneliness)) +
  geom_boxplot(outlier.shape = NA) +               # no separate outlier dots
  geom_jitter(width = 0.2, height = 0.2, alpha = 0.1) +   # every person
  labs(x = "Age group", y = "Loneliness score (3 to 9)")

# 4. Two numeric variables with a loess smoother
set.seed(2021)
ggplot(brief, aes(x = age, y = loneliness)) +
  geom_jitter(height = 0.2, alpha = 0.1) +
  geom_smooth(method = "loess") +                  # a curve that can bend
  labs(x = "Age (years)", y = "Loneliness score (3 to 9)")

# 5. One panel per group: facet_wrap() and facet_grid()
ggplot(brief, aes(x = loneliness)) +
  geom_histogram(binwidth = 1, fill = "#0B7B6B", colour = "white") +
  facet_wrap(~ age_group) +                        # one panel per age group
  labs(x = "Loneliness score (3 to 9)", y = "Number of people")
set.seed(2021)
ggplot(brief, aes(x = support, y = loneliness)) +
  geom_jitter(height = 0.2, alpha = 0.2) +
  geom_smooth(method = "lm") +                     # a straight line per panel
  facet_grid(gender ~ age_group) +                 # rows: gender; columns: age
  labs(x = "Social support (1 to 7)", y = "Loneliness score (3 to 9)")
table(brief$gender, brief$age_group)               # people in each panel

# 6. Colour, a theme, and saving the figure
p <- ggplot(brief, aes(x = age_group, y = loneliness, fill = gender)) +
  geom_boxplot() +
  scale_fill_manual(values = c("#E69F00", "#56B4E9", "#009E73")) +   # Okabe-Ito
  labs(x = "Age group", y = "Loneliness score (3 to 9)", fill = "Gender") +
  theme_minimal(base_size = 12)                    # a plain theme
p                                                  # show the plot
ggsave("loneliness_age_gender.png", p, width = 7, height = 4.5, dpi = 300)
