#!/usr/bin/env Rscript
# Deterministic teaching data: this is not an empirical result or a simulation study.
library(ggplot2)
offset_x <- c(-0.6, -0.3, 0, 0.3, 0.6)
offset_y <- c(0.3, 0.6, -0.2, 0.1, -0.8)
centres <- data.frame(individual = factor(paste0("ID ", 1:5)),
                      x_mean = 1:5,
                      y_mean = c(1.3, 1.7, 3.0, 3.5, 4.4))
observations <- centres[rep(seq_len(nrow(centres)), each = 5), ]
observations$x <- observations$x_mean + rep(offset_x, 5) *
  (1 + 0.1 * as.integer(observations$individual))
observations$y <- observations$y_mean + rep(offset_y, 5) *
  (1 + 0.08 * as.integer(observations$individual))
panels <- rbind(
  data.frame(individual = observations$individual, x = observations$x,
             y = observations$y, panel = "Observed scores"),
  data.frame(individual = centres$individual, x = centres$x_mean,
             y = centres$y_mean, panel = "Differences among individuals"),
  data.frame(individual = observations$individual,
             x = observations$x - observations$x_mean,
             y = observations$y - observations$y_mean,
             panel = "Deviations within individuals")
)
panels$panel <- factor(panels$panel, levels = c("Observed scores",
  "Differences among individuals", "Deviations within individuals"))
p <- ggplot(panels, aes(x, y, colour = individual)) +
  geom_point(aes(shape = individual), size = 2.7, alpha = 0.85) +
  facet_wrap(~ panel, scales = "free", nrow = 1) +
  scale_colour_brewer(palette = "Dark2", name = "Individual") +
  scale_shape_discrete(name = "Individual") +
  labs(x = "Trait A: score or deviation", y = "Trait B: score or deviation") +
  theme_minimal(base_size = 12) +
  theme(legend.position = "bottom", panel.grid.minor = element_blank(),
        strip.text = element_text(face = "bold"))
dir.create("tutorial/figures", showWarnings = FALSE, recursive = TRUE)
ggsave("tutorial/figures/two-level-teaching.png", p, width = 10.8,
       height = 4.1, dpi = 180)
ggsave("tutorial/figures/two-level-teaching.pdf", p, width = 10.8,
       height = 4.1)
