Data and code
Find the datasets, saved results, and scripts used in the lessons here. For the commands to prepare data, fit models, and reproduce results, see Report and reproduce.
What the companion provides
The main examples use Arctic charr and ten-score dogs. Use the bundled inputs to start from the data, the Figure Gallery to redraw the manuscript figures, or the draw guide to recalculate the archived intervals.
Data availability and authorised inputs
All three example datasets are bundled with the repository. Read the data notes and data-use and acknowledgment information before reusing the dog data or redistributing tutorial materials.
- Arctic charr: workbook and preparation script
- Dogs: modified CSV with randomized IDs and preparation script
- Red knots: compiled CSV and preparation script
Run the two main examples
Download the reproduction ZIP, then follow the commands to prepare the data, recalculate intervals or fit the models.
Figure gallery
This gallery gives the R source used to draw the analysis figures in the manuscript. Open a panel at full size, copy the code from its section, or download the same script. Figures 2–4 use bundled aggregate estimates and extracted ordination coordinates. Figure 1 is a conceptual diagram explained in the Framework lesson, not an output of the data analysis, so it is not included in this analysis-figure gallery. These plotting scripts do not refit the empirical models or rerun the parametric bootstrap. The charr and dog lessons show how to prepare the observations and fit the models in glmmTMB and gllvmTMB.
The figure-gallery README gives the commands, required R packages, and a file-by-file input manifest. The code blocks below are included directly from the downloadable scripts, so the displayed code and the files run by the commands stay in sync.
The interval endpoints and asterisks are read from the saved, unrounded summaries. They are model-conditional percentile limits among the retained paired refits. Their nominal coverage has not been established. The ordination coordinates are fit-derived and have had individual identifiers removed. Dog coordinates remain pseudonymous study data; the prepublication data review requirement still applies.
Figure 2: Arctic charr correlations, ordinations, communality and repeatability
The trait numbers in panels A–F refer to the charr key. Correlation panels show point estimates above the diagonal and the lower then upper 95% limits below it. Panels C and D show two separate ordinations. The stored between- and within-fish scores and loadings have already been rotated separately by varimax; the plotting script reads those rotated coordinates. Panel E gives communality and panel F gives repeatability. Point symbols mark estimates, and capped horizontal lines show 95% parametric-bootstrap percentile limits for every communality estimate. A short line means the limits are close, not that an interval is missing; the linked tables give the exact endpoints.
Inputs: correlations, communalities, repeatabilities, rotated score coordinates, rotated loadings, and trait key. The correlation, communality and repeatability summaries use 1,066 retained paired refits from the archived campaign.
Complete R code for Figure 2
Dependencies: ggplot2, patchwork, and ggrepel.
#!/usr/bin/env Rscript
# Recreate manuscript Figure 2 (Arctic charr) from the bundled aggregate inputs.
# Run from the repository root: Rscript tutorial/downloads/figure-gallery/make-figure-2.R
# This script draws archived estimates; it does not refit models or rerun bootstraps.
suppressPackageStartupMessages({
library(ggplot2)
library(patchwork)
library(ggrepel)
})
input_dir <- "tutorial/downloads/figure-gallery/data"
output_dir <- "tutorial/figures/figure-gallery"
dir.create(output_dir, recursive = TRUE, showWarnings = FALSE)
key <- read.csv(file.path(input_dir, "charr-trait-key.csv"),
stringsAsFactors = FALSE)
corr <- read.csv(file.path(input_dir, "charr-correlations.csv"),
stringsAsFactors = FALSE)
comm <- read.csv(file.path(input_dir, "charr-communalities.csv"),
stringsAsFactors = FALSE)
rep <- read.csv(file.path(input_dir, "charr-repeatability.csv"),
stringsAsFactors = FALSE)
ord <- read.csv(file.path(input_dir, "charr-ordination-coordinates.csv"),
stringsAsFactors = FALSE)
load <- read.csv(file.path(input_dir, "charr-ordination-loadings.csv"),
stringsAsFactors = FALSE)
traits <- key$trait
stopifnot(nrow(key) == 9L, identical(key$trait_number, 1:9),
nrow(corr) == 72L, nrow(comm) == 18L, nrow(rep) == 9L,
all(corr$paired_refits == 1066L),
all(comm$paired_refits == 1066L),
all(rep$paired_refits == 1066L),
nrow(subset(ord, level == "Between fish")) == 1185L,
nrow(subset(ord, level == "Within fish")) == 2370L,
nrow(load) == 18L,
all(corr$trait_1 %in% traits), all(corr$trait_2 %in% traits),
setequal(comm$trait, traits),
setequal(comm$level, c("Between fish", "Within fish")),
!anyDuplicated(comm[c("trait", "level")]),
setequal(rep$trait, traits),
all(is.finite(comm$lower_95)), all(is.finite(comm$upper_95)),
all(comm$lower_95 < comm$upper_95),
all(comm$lower_95 <= comm$estimate & comm$estimate <= comm$upper_95),
all(is.finite(rep$lower_95)), all(is.finite(rep$upper_95)),
all(rep$lower_95 < rep$upper_95),
all(rep$lower_95 <= rep$estimate & rep$estimate <= rep$upper_95))
theme_set(theme_minimal(base_size = 9) +
theme(panel.grid.minor = element_blank()))
matrix_panel <- function(level, title) {
dat <- corr[corr$level == level, , drop = FALSE]
i <- match(dat$trait_1, traits)
j <- match(dat$trait_2, traits)
stopifnot(nrow(dat) == 36L, !anyNA(i), !anyNA(j))
upper <- data.frame(
x = j, y = 10 - i, value = dat$correlation,
label = sprintf("%.2f%s", dat$correlation,
ifelse(dat$lower_95 > 0 | dat$upper_95 < 0, "*", ""))
)
lower <- data.frame(x = i, y = 10 - j,
label = sprintf("%.2f\n%.2f", dat$lower_95,
dat$upper_95))
grid <- expand.grid(x = 1:9, y = 1:9)
ggplot() +
geom_tile(data = grid, aes(x, y), fill = "white", colour = "grey88") +
geom_tile(data = upper, aes(x, y, fill = value), colour = "white") +
geom_text(data = upper, aes(x, y, label = label), size = 3.0) +
geom_text(data = lower, aes(x, y, label = label), size = 2.8,
lineheight = 0.85) +
scale_fill_gradient2(low = "#b54742", mid = "white", high = "#5684a6",
limits = c(-1, 1), name = "Correlation") +
scale_x_continuous(breaks = 1:9, position = "top") +
scale_y_continuous(breaks = 9:1, labels = 1:9) +
coord_equal() +
labs(title = title, x = NULL, y = NULL) +
theme(panel.grid = element_blank(), legend.position = "none",
axis.text = element_text(size = 7))
}
ordination_panel <- function(level, title) {
points <- ord[ord$level == level, , drop = FALSE]
arrows <- load[load$level == level, , drop = FALSE]
scale_factor <- 0.75 * min(diff(range(points$axis1)),
diff(range(points$axis2))) /
max(abs(as.matrix(arrows[, c("axis1", "axis2")])))
arrows$x <- arrows$axis1 * scale_factor
arrows$y <- arrows$axis2 * scale_factor
arrows$label <- sprintf("%d", arrows$trait_number)
arrows$nudge_x <- ifelse(level == "Between fish" & arrows$label == "7", 0.55, 0)
arrows$nudge_y <- ifelse(level == "Between fish" & arrows$label == "7", -0.55, 0)
xr <- range(c(points$axis1, arrows$x))
yr <- range(c(points$axis2, arrows$y))
xr <- xr + c(-1, 1) * diff(xr) * 0.14
yr <- yr + c(-1, 1) * diff(yr) * 0.14
ggplot(points, aes(axis1, axis2)) +
geom_hline(yintercept = 0, colour = "grey82") +
geom_vline(xintercept = 0, colour = "grey82") +
geom_point(alpha = 0.12, size = 0.45, colour = "grey35") +
geom_segment(data = arrows, aes(x = 0, y = 0, xend = x, yend = y),
inherit.aes = FALSE, colour = "#0072B2", linewidth = 0.45,
arrow = grid::arrow(length = grid::unit(1.4, "mm"))) +
geom_text_repel(data = arrows, aes(x, y, label = label),
inherit.aes = FALSE, nudge_x = arrows$nudge_x,
nudge_y = arrows$nudge_y, seed = 13, size = 3,
colour = "#0072B2", max.overlaps = Inf,
min.segment.length = 0) +
coord_equal(xlim = xr, ylim = yr, clip = "off") +
labs(title = title, x = "Axis 1", y = "Axis 2")
}
comm$trait_number <- key$trait_number[match(comm$trait, traits)]
comm$y <- 10 - comm$trait_number +
ifelse(comm$level == "Between fish", 0.13, -0.13)
comm$level <- factor(comm$level, levels = c("Between fish", "Within fish"))
communality_panel <- ggplot(comm, aes(estimate, y, colour = level,
shape = level)) +
geom_point(size = 1.6) +
geom_errorbar(aes(xmin = lower_95, xmax = upper_95), orientation = "y",
width = 0.09, linewidth = 0.65) +
scale_colour_manual(values = c("Between fish" = "#0072B2",
"Within fish" = "#D55E00")) +
scale_shape_manual(values = c("Between fish" = 16, "Within fish" = 17)) +
scale_x_continuous(breaks = seq(0, 1, 0.25),
expand = expansion(mult = c(0, 0))) +
coord_cartesian(xlim = c(0, 1.04)) +
scale_y_continuous(breaks = 9:1, labels = 1:9) +
labs(title = "E Communality", x = "Shared variance / variance at this level",
y = "Trait number", colour = NULL, shape = NULL) +
theme(legend.position = "bottom", legend.direction = "horizontal")
rep$trait_number <- key$trait_number[match(rep$trait, traits)]
rep$y <- 10 - rep$trait_number
repeatability_panel <- ggplot(rep, aes(estimate, y)) +
geom_segment(aes(x = lower_95, xend = upper_95, yend = y),
colour = "#0072B2", linewidth = 0.65) +
geom_point(colour = "#25333D", shape = 18, size = 1.8) +
scale_x_continuous(breaks = seq(0, 1, 0.25),
expand = expansion(mult = c(0, 0))) +
coord_cartesian(xlim = c(0, 1.04)) +
scale_y_continuous(breaks = 9:1, labels = 1:9) +
labs(title = "F Repeatability", x = "Between / (between + within)",
y = "Trait number")
figure <-
(matrix_panel("Between fish", "A Between-fish correlations") |
matrix_panel("Within fish", "B Within-fish correlations")) /
(ordination_panel("Between fish", "C Between-fish ordination") |
ordination_panel("Within fish", "D Within-fish ordination")) /
(communality_panel | repeatability_panel) +
plot_layout(heights = c(1.15, 1, 0.78))
ggsave(file.path(output_dir, "figure-2-charr.png"), figure,
width = 8.1, height = 11.4, dpi = 300, bg = "white")
ggsave(file.path(output_dir, "figure-2-charr.pdf"), figure,
width = 8.1, height = 11.4, device = cairo_pdf, bg = "white")
cat("PASS FIGURE 2: nine traits; 1,066 paired refits; E communality; F repeatability\n")Figure 3: between- and within-dog correlations
The matrices show the same ten scores in the same order. Panel A gives correlations between dogs; panel B gives correlations among repeated scores within dogs. Point estimates appear above the diagonal and the lower then upper percentile limits below it. The 45-degree labels are listed in the dog trait key.
Inputs: aggregate correlations and trait key. The saved intervals use 1,095 retained paired refits. The script expands each unordered trait pair into the two displayed matrix cells; it does not rerun the bootstrap.
Complete R code for Figure 3
Dependencies: ggplot2 and patchwork.
# Recreate manuscript Figure 3 from bundled, aggregate dog correlation results.
# Run from the repository root:
# Rscript --vanilla tutorial/downloads/figure-gallery/make-figure-3.R
# This script does not fit models or regenerate bootstrap intervals.
suppressPackageStartupMessages({
library(ggplot2)
library(patchwork)
})
input_dir <- "tutorial/downloads/figure-gallery/data"
output_dir <- "tutorial/figures/figure-gallery"
dir.create(output_dir, recursive = TRUE, showWarnings = FALSE)
correlations <- read.csv(
file.path(input_dir, "dogs-correlations.csv"),
stringsAsFactors = FALSE,
check.names = FALSE
)
trait_key <- read.csv(
file.path(input_dir, "dogs-trait-key.csv"),
stringsAsFactors = FALSE,
check.names = FALSE
)
expected_traits <- c(
"Stranger-directed aggression",
"Dog-directed aggression",
"Dog-directed fear",
"Trainability",
"Chasing",
"Nonsocial fear",
"Touch sensitivity",
"Excitability",
"Attachment and attention seeking",
"Energy"
)
expected_levels <- c("Between dogs", "Within dogs")
stopifnot(
nrow(correlations) == 90L,
nrow(trait_key) == 10L,
identical(trait_key$number, 1:10),
identical(trait_key$trait, expected_traits),
setequal(unique(correlations$level), expected_levels),
all(correlations$retained_paired_refits == 1095L),
all(correlations$trait1_number < correlations$trait2_number),
!anyDuplicated(correlations[c("level", "trait1_number", "trait2_number")]),
all(is.finite(correlations$estimate)),
all(is.finite(correlations$lower_95)),
all(is.finite(correlations$upper_95)),
all(correlations$lower_95 <= correlations$estimate),
all(correlations$estimate <= correlations$upper_95),
all(correlations$lower_95 >= -1),
all(correlations$upper_95 <= 1)
)
# Check the table’s labels against the explicit key before using their order.
for (i in seq_len(nrow(correlations))) {
row <- correlations[i, ]
stopifnot(
identical(row$trait1, expected_traits[row$trait1_number]),
identical(row$trait2, expected_traits[row$trait2_number])
)
}
# Use a common precision in the figure. Sign markers use unrounded endpoints.
format_cell <- function(x) {
rounded <- round(x, 3)
sub("^(-?)0[.]", "\\1.", sprintf("%.3f", ifelse(rounded == 0, 0, rounded)))
}
# Expand each unordered pair into two matrix cells: estimates above the
# diagonal and lower/upper percentile limits below it.
panel_levels <- c("Between dogs", "Within dogs")
cell_rows <- vector("list", nrow(correlations) * 2L)
out <- 0L
for (k in seq_len(nrow(correlations))) {
r <- correlations[k, ]
i <- r$trait1_number
j <- r$trait2_number
estimate_text <- paste0(
format_cell(r$estimate),
if (r$lower_95 > 0 || r$upper_95 < 0) "*" else ""
)
interval_text <- paste(format_cell(r$lower_95), format_cell(r$upper_95), sep = "\n")
out <- out + 1L
cell_rows[[out]] <- data.frame(
level = r$level, i = i, j = j, estimate = r$estimate,
label = estimate_text, stringsAsFactors = FALSE
)
out <- out + 1L
cell_rows[[out]] <- data.frame(
level = r$level, i = j, j = i, estimate = NA_real_,
label = interval_text, stringsAsFactors = FALSE
)
}
cells <- do.call(rbind, cell_rows)
diagonal <- expand.grid(i = 1:10, level = panel_levels, stringsAsFactors = FALSE)
diagonal$j <- diagonal$i
diagonal$estimate <- NA_real_
diagonal$label <- ""
cells <- rbind(cells, diagonal)
cells$level <- factor(cells$level, levels = panel_levels)
cells$x <- factor(cells$j, levels = 1:10)
cells$y <- factor(cells$i, levels = 10:1)
matrix_panel <- function(level, title) {
panel_cells <- cells[as.character(cells$level) == level, ]
ggplot(panel_cells, aes(x = x, y = y)) +
geom_tile(aes(fill = estimate), colour = "white", linewidth = 0.35) +
geom_text(aes(label = label), size = 3.0, lineheight = 0.9, colour = "grey10") +
coord_fixed() +
scale_fill_gradient2(
low = "#bb675d", mid = "#fafafa", high = "#6595b9",
limits = c(-1, 1), na.value = "grey94", guide = "none"
) +
scale_x_discrete(labels = setNames(expected_traits, as.character(1:10))) +
scale_y_discrete(labels = setNames(expected_traits, as.character(1:10))) +
labs(title = title, x = NULL, y = NULL) +
theme_minimal(base_size = 10) +
theme(
panel.grid = element_blank(),
axis.text.y = element_text(colour = "grey15", size = 8.5),
axis.text.x = element_text(
colour = "grey15", size = 8, angle = 45, hjust = 1, vjust = 1
),
axis.ticks = element_blank(),
plot.title = element_text(face = "bold", size = 11, hjust = 0),
plot.margin = margin(8, 12, 8, 12)
)
}
between <- matrix_panel("Between dogs", "A Between dogs") +
theme(axis.text.x = element_blank(), axis.ticks.x = element_blank())
within <- matrix_panel("Within dogs", "B Within dogs")
p <- between / within + plot_layout(heights = c(1, 1))
ggsave(
file.path(output_dir, "figure-3-dog-correlations.png"),
p, width = 10, height = 13.4, units = "in", dpi = 240,
bg = "white"
)
ggsave(
file.path(output_dir, "figure-3-dog-correlations.pdf"),
p, width = 10, height = 13.4, units = "in", device = grDevices::pdf,
bg = "white"
)
cat("PASS GFG-F3: 90 aggregate pairs, 180 off-diagonal cells, 10 keyed traits; outputs written.\n")Figure 4: dog ordinations, communality and repeatability
The ordination uses all three two-axis projections for each level. Between-dog and within-dog axes are rotated separately, so the two rows are not a shared coordinate system. Arrows are multiplied by five for display. Panel C shows communality before panel D shows repeatability. Its capped interval lines are present for all ten traits at both levels. The key below the figure gives the full names for all ten traits.
Inputs: ID-free rotated scores, rotated loadings, communality, repeatability, and the full trait key. These intervals use 1,095 retained paired refits. The source tables are already rotated/extracted aggregates; the script does not refit the model or recompute the bootstrap.
Complete R code for Figure 4
Dependencies: ggplot2 and patchwork.
#!/usr/bin/env Rscript
# Rebuild the dog ordination, communality, and repeatability figure.
#
# Inputs are ID-free, fit-derived score coordinates and aggregate summary
# tables. The source bootstrap draws and fitted model objects are not included.
# This script recreates the displayed figure; it does not rerun model fitting or
# the parametric bootstrap.
#
# Dependencies: ggplot2, patchwork.
# From the repository root:
# Rscript --vanilla tutorial/downloads/figure-gallery/make-figure-4.R
# Outputs: tutorial/figures/figure-gallery/figure-4.png and .pdf
suppressPackageStartupMessages({
library(ggplot2)
library(patchwork)
})
data_dir <- "tutorial/downloads/figure-gallery/data"
out_dir <- "tutorial/figures/figure-gallery"
dir.create(out_dir, recursive = TRUE, showWarnings = FALSE)
scores <- read.csv(file.path(data_dir, "dogs-figure4-scores-id-free.csv"),
stringsAsFactors = FALSE)
loadings <- read.csv(file.path(data_dir, "dogs-figure4-loadings.csv"),
stringsAsFactors = FALSE)
key <- read.csv(file.path(data_dir, "dogs-figure4-trait-key.csv"),
stringsAsFactors = FALSE)
comm <- read.csv(file.path(data_dir, "dogs-figure4-communalities.csv"),
stringsAsFactors = FALSE)
repeatability <- read.csv(file.path(data_dir, "dogs-figure4-repeatability.csv"),
stringsAsFactors = FALSE)
expected_traits <- key$trait
stopifnot(nrow(key) == 10L,
identical(key$number, 1:10),
"trait_label" %in% names(key),
nrow(scores) == 1000L,
identical(as.integer(table(factor(scores$level,
levels = c("B", "W")))),
c(100L, 900L)),
identical(names(scores), c("level", "axis1", "axis2", "axis3")),
!anyDuplicated(loadings[c("level", "trait")]),
nrow(loadings) == 20L,
setequal(loadings$trait, expected_traits),
nrow(comm) == 30L,
nrow(repeatability) == 10L,
all(comm$retained_paired_refits == 1095L),
all(repeatability$retained_paired_refits == 1095L),
all(is.finite(as.matrix(scores[, c("axis1", "axis2", "axis3")]))) ,
all(is.finite(comm$lower_95)), all(is.finite(comm$upper_95)),
all(comm$lower_95 < comm$upper_95),
all(comm$lower_95 <= comm$estimate & comm$estimate <= comm$upper_95),
all(repeatability$lower_95 <= repeatability$estimate &
repeatability$estimate <= repeatability$upper_95))
axes <- list(c(1L, 2L), c(1L, 3L), c(2L, 3L))
axis_names <- c("Axes 1-2", "Axes 1-3", "Axes 2-3")
score_panels <- list()
loading_panels <- list()
for (lev in c("B", "W")) {
s <- scores[scores$level == lev, , drop = FALSE]
l <- loadings[loadings$level == lev, , drop = FALSE]
l <- l[match(expected_traits, l$trait), , drop = FALSE]
stopifnot(nrow(s) == if (lev == "B") 100L else 900L,
identical(l$trait, expected_traits),
setequal(names(l), c("level", "trait", "axis1", "axis2", "axis3")))
for (k in seq_along(axes)) {
ax <- axes[[k]]
pair <- axis_names[[k]]
score_panels[[paste(lev, pair)]] <- data.frame(
level = lev, pair = pair,
x = s[[paste0("axis", ax[[1]])]],
y = s[[paste0("axis", ax[[2]])]]
)
loading_panels[[paste(lev, pair)]] <- data.frame(
level = lev, pair = pair,
trait_number = key$number,
x = l[[paste0("axis", ax[[1]])]] * 5,
y = l[[paste0("axis", ax[[2]])]] * 5
)
}
}
score_panels <- do.call(rbind, score_panels)
loading_panels <- do.call(rbind, loading_panels)
score_panels$pair <- factor(score_panels$pair, levels = axis_names)
loading_panels$pair <- factor(loading_panels$pair, levels = axis_names)
loading_panels$label_x <- NA_real_
loading_panels$label_y <- NA_real_
for (lev in c("B", "W")) for (pair in axis_names) {
idx <- which(loading_panels$level == lev & loading_panels$pair == pair)
ordering <- idx[order(atan2(loading_panels$y[idx], loading_panels$x[idx]))]
angle <- seq(-pi, pi, length.out = 11L)[-11L]
loading_panels$label_x[ordering] <- 4.15 * cos(angle)
loading_panels$label_y[ordering] <- 4.15 * sin(angle)
}
ordination_panel <- function(lev, title, point_colour) {
s <- score_panels[score_panels$level == lev, , drop = FALSE]
l <- loading_panels[loading_panels$level == lev, , drop = FALSE]
highlighted <- subset(l, level == "B" & pair == axis_names[[2]] &
trait_number %in% c(3L, 7L))
highlighted$line <- ifelse(highlighted$trait_number == 3L, "solid", "dashed")
ggplot() +
geom_hline(yintercept = 0, colour = "grey82", linewidth = 0.35) +
geom_vline(xintercept = 0, colour = "grey82", linewidth = 0.35) +
geom_point(data = s, aes(x, y), colour = point_colour,
alpha = if (lev == "B") 0.36 else 0.13,
size = if (lev == "B") 0.38 else 0.24) +
geom_segment(data = l, aes(x = 0, y = 0, xend = x, yend = y),
colour = "#26343B", linewidth = 0.38,
arrow = grid::arrow(length = grid::unit(1.2, "mm"))) +
geom_segment(data = l,
aes(x = x, y = y, xend = label_x, yend = label_y),
colour = "grey55", linewidth = 0.20) +
geom_segment(data = highlighted,
aes(x = 0, y = 0, xend = x, yend = y,
linetype = line),
colour = "#17252D", linewidth = 0.65, show.legend = FALSE,
arrow = grid::arrow(length = grid::unit(1.4, "mm"))) +
geom_segment(data = highlighted,
aes(x = x, y = y, xend = label_x, yend = label_y,
linetype = line),
colour = "#17252D", linewidth = 0.45, show.legend = FALSE) +
scale_linetype_identity() +
geom_label(data = l,
aes(x = label_x, y = label_y,
label = as.character(trait_number)),
size = 2.25, linewidth = 0, label.padding =
grid::unit(0.04, "lines"), fill = "white",
colour = "#17252D") +
facet_wrap(~pair, nrow = 1) +
coord_equal(xlim = c(-5, 5), ylim = c(-5, 5), clip = "off") +
labs(title = title,
x = "Conditional score (arrows show loadings scaled by 5)",
y = "Conditional score") +
theme_minimal(base_size = 8.5) +
theme(panel.grid.minor = element_blank(),
strip.text = element_text(face = "bold", size = 8),
plot.title = element_text(face = "bold", size = 10),
plot.margin = margin(4, 7, 4, 4))
}
comm <- subset(comm, level %in% c("Between dogs", "Within dogs"))
comm$trait <- factor(comm$trait, levels = rev(key$trait_label))
comm$level <- factor(comm$level, levels = c("Between dogs", "Within dogs"))
stopifnot(nrow(comm) == 20L, !anyNA(comm$trait), !anyNA(comm$level))
communality_panel <- ggplot(comm, aes(x = estimate, y = trait,
colour = level, shape = level)) +
geom_point(position = position_dodge(width = 0.56), size = 1.6) +
geom_errorbar(aes(xmin = lower_95, xmax = upper_95), orientation = "y",
position = position_dodge(width = 0.56),
width = 0.12, linewidth = 0.68) +
scale_colour_manual(values = c("Between dogs" = "#0072B2",
"Within dogs" = "#D55E00")) +
scale_shape_manual(values = c("Between dogs" = 16,
"Within dogs" = 17)) +
scale_x_continuous(breaks = seq(0, 1, 0.25),
expand = expansion(mult = c(0, 0))) +
coord_cartesian(xlim = c(0, 1.04)) +
labs(title = "C Communality",
x = "Shared variance / variance at this level",
y = NULL, colour = NULL, shape = NULL) +
theme_minimal(base_size = 8.5) +
theme(panel.grid.minor = element_blank(),
plot.title = element_text(face = "bold", size = 10),
legend.position = "bottom")
repeatability$trait <- factor(repeatability$trait,
levels = rev(key$trait_label))
stopifnot(!anyNA(repeatability$trait))
repeatability_panel <- ggplot(repeatability,
aes(x = estimate, y = trait)) +
geom_segment(aes(x = lower_95, xend = upper_95, yend = trait),
colour = "#0072B2", linewidth = 0.62) +
geom_point(colour = "#25333D", shape = 18, size = 1.8) +
scale_x_continuous(breaks = seq(0, 1, 0.25),
expand = expansion(mult = c(0, 0))) +
coord_cartesian(xlim = c(0, 1.04)) +
labs(title = "D Repeatability",
x = "Between / (between + within variance)", y = NULL) +
theme_minimal(base_size = 8.5) +
theme(panel.grid.minor = element_blank(),
plot.title = element_text(face = "bold", size = 10),
# Panels C and D share trait rows. Keep one readable trait-name column
# on C rather than repeating long labels beside the narrow D panel.
axis.text.y = element_blank(),
axis.ticks.y = element_blank())
key_lines <- split(seq_len(nrow(key)), ceiling(seq_len(nrow(key)) / 5))
trait_key <- paste(vapply(key_lines, function(i) {
paste(sprintf("%d %s", key$number[i], key$trait_label[i]), collapse = " | ")
}, character(1)), collapse = "\n")
figure <- ordination_panel("B", "A Between-dog ordination", "#17699C") /
ordination_panel("W", "B Within-dog ordination", "#BD5C14") /
(communality_panel | repeatability_panel) +
plot_layout(heights = c(1, 1, 0.82)) +
plot_annotation(caption = paste("Trait key:", trait_key)) &
theme(plot.caption = element_text(size = 7.8, hjust = 0,
margin = margin(t = 5)))
# Render both formats before replacing either existing figure.
scratch <- tempfile("figure-4-", tmpdir = out_dir)
dir.create(scratch)
on_error <- function(message) {
if (length(published)) unlink(file.path(out_dir, published))
restored <- vapply(backed_up, function(name) {
file.rename(file.path(scratch, paste0("previous-", name)),
file.path(out_dir, name))
}, logical(1))
if (all(restored)) unlink(scratch, recursive = TRUE)
if (!all(restored)) {
stop(message, ". Recovery files are in ", scratch, call. = FALSE)
}
stop(message, call. = FALSE)
}
# Move the PDF first so a PDF locked by a viewer leaves both outputs alone.
files <- c("figure-4.pdf", "figure-4.png")
backed_up <- published <- character()
tryCatch({
ggsave(file.path(scratch, "figure-4.png"), figure,
width = 7.2, height = 9.3, dpi = 300, bg = "white")
ggsave(file.path(scratch, "figure-4.pdf"), figure,
width = 7.2, height = 9.3, device = cairo_pdf, bg = "white")
for (name in files) {
original <- file.path(out_dir, name)
if (file.exists(original)) {
if (!file.rename(original, file.path(scratch, paste0("previous-", name)))) {
stop("Could not move the existing ", name, ". Close it and retry.")
}
backed_up <- c(backed_up, name)
}
}
for (name in files) {
if (!file.rename(file.path(scratch, name), file.path(out_dir, name))) {
stop("Could not install the new ", name)
}
published <- c(published, name)
}
}, error = function(err) on_error(conditionMessage(err)))
unlink(scratch, recursive = TRUE)
cat("PASS FIGURE 4: 100 between-dog and 900 within-dog conditional scores;",
"all three projections per level; communality before repeatability;",
"1095 archived paired refits per interval summary.\n")For the gllvmTMB extraction and separate varimax rotation steps used in the ordination lessons, see Ordination: seeing the fitted shared structure. That page shows how to rotate loadings and scores together and check that their reconstructed shared covariance is unchanged. The figure-generation scripts here start from the resulting coordinates so readers can regenerate the artwork without repeating the model fits.
Six-trait red-knot extension
- The six-trait red-knot extension has its own six-panel figure, point estimates, correlations, 2/2 fit diagnostics, and two-engine rank comparison. Scripts are available for the matched 2/2 fits and rank comparison. For this same fit, see the 95% intervals, campaign record, retained target draws, and bootstrap runner.
Simulated random slopes
See the temperature lesson and its reproduction instructions or download the complete R script.


