# dbRDA in R: distance-based redundancy analysis
# https://tidyecology.com/posts/constrained-ordination-dbrda/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-05-01

## ---- setup ----
library(vegan)
library(ggplot2)
library(dplyr)

paper <- "#f5f4ee"; ink <- "#16241d"; forest <- "#275139"
gold  <- "#cda23f"; abandoned <- "#b5534e"; faint <- "#5d6b61"; line <- "#dad9ca"

theme_te <- theme_minimal(base_size = 12) +
  theme(panel.grid.minor = element_blank(),
        panel.grid.major = element_line(colour = line, linewidth = 0.3),
        plot.background = element_rect(fill = paper, colour = NA),
        panel.background = element_rect(fill = paper, colour = NA),
        axis.title = element_text(colour = ink),
        axis.text = element_text(colour = faint),
        plot.title = element_text(colour = ink, face = "bold"))

## ---- data ----
set.seed(20)
n <- 40
moisture <- round(runif(n, 0, 10), 1)
nitrogen <- round(runif(n, 0, 10), 1)

species <- sprintf("sp%02d", 1:14)
opt_m <- seq(1, 9, length.out = 14)            # moisture optimum per species
opt_n <- sample(seq(1, 9, length.out = 14))    # nitrogen optimum, independent of moisture
w <- 2.3
lambda <- sapply(seq_along(species), function(i)
  12 * exp(-((moisture - opt_m[i])^2 + (nitrogen - opt_n[i])^2) / (2 * w^2)))
comm <- matrix(rpois(length(lambda), as.vector(lambda)), nrow = n)
colnames(comm) <- species
rownames(comm) <- sprintf("S%02d", 1:n)

env <- data.frame(moisture = moisture, nitrogen = nitrogen)
comm[1:5, 1:7]

## ---- model ----
mod <- dbrda(comm ~ moisture + nitrogen, data = env, distance = "bray")
mod

## ---- rsq ----
RsquareAdj(mod)

## ---- anova-overall ----
set.seed(20)
anova(mod, permutations = 999)

## ---- anova-terms ----
set.seed(20)
anova(mod, by = "terms", permutations = 999)

## ---- anova-axis ----
set.seed(20)
anova(mod, by = "axis", permutations = 999)

## ---- fig-dbrda ----
scl <- 2
site_sc <- as.data.frame(scores(mod, display = "sites", scaling = scl, choices = 1:2))
bp      <- as.data.frame(scores(mod, display = "bp",    scaling = scl, choices = 1:2))
names(site_sc) <- c("AX1", "AX2")
names(bp)      <- c("AX1", "AX2")
site_sc$moisture <- moisture
site_sc$nitrogen <- nitrogen

# scale the predictor arrows to sit over the site cloud
mul <- 0.9 * max(abs(as.matrix(site_sc[, 1:2]))) / max(sqrt(rowSums(bp^2)))
bp$lab <- rownames(bp)
bp$x <- bp$AX1 * mul
bp$y <- bp$AX2 * mul
# place each label just beyond its arrow tip, on the side the arrow points to
bp$len <- sqrt(bp$x^2 + bp$y^2)
bp$hj <- 0.5 * (1 - bp$x / bp$len)
bp$vj <- 0.5 * (1 - bp$y / bp$len)

eig <- mod$CCA$eig
lab1 <- sprintf("dbRDA1 (%.0f%% of fitted)", 100 * eig[1] / sum(eig))
lab2 <- sprintf("dbRDA2 (%.0f%% of fitted)", 100 * eig[2] / sum(eig))

ggplot(site_sc, aes(AX1, AX2)) +
  geom_hline(yintercept = 0, color = "#e2e1d4") +
  geom_vline(xintercept = 0, color = "#e2e1d4") +
  geom_point(aes(color = moisture, size = nitrogen)) +
  geom_segment(data = bp, aes(x = 0, y = 0, xend = x, yend = y), inherit.aes = FALSE,
               arrow = arrow(length = unit(0.2, "cm")), color = "#16241d", linewidth = 0.9) +
  geom_text(data = bp, aes(x = x * 1.04, y = y * 1.04, label = lab,
                           hjust = hj, vjust = vj), inherit.aes = FALSE,
            color = "#16241d", fontface = "bold", size = 3.6) +
  expand_limits(x = bp$x * 1.3, y = bp$y * 1.12) +
  scale_color_gradient(low = "#c9b458", high = "#1d5b4e", name = "Moisture") +
  scale_size_continuous(range = c(1.3, 5), name = "Nitrogen") +
  labs(x = lab1, y = lab2) +
  coord_equal() +
  theme_te
