plot_trait_heatmap(traits, groups)

Heatmap of standardised trait values across species or communities, with optional group annotation.

ggplot2traits
Args:traits — species × traits matrixgroups — optional grouping factorscale=TRUE
plot_trait_heatmap <- function(traits, groups = NULL, scale = TRUE,
                             low = "#2471a3", mid = "white", high = "#c0392b") {
  library(ggplot2); library(reshape2)
  
  m <- as.matrix(traits)
  if (scale) m <- scale(m)
  
  df <- melt(m, varnames = c("species", "trait"), value.name = "value")
  if (!is.null(groups))
    df$group <- groups[as.character(df$species)]
  
  p <- ggplot(df, aes(trait, species, fill = value)) +
    geom_tile(colour = "white", linewidth = 0.3) +
    scale_fill_gradient2(low = low, mid = mid, high = high, midpoint = 0,
                         na.value = "grey80") +
    labs(fill = if (scale) "z-score" else "value") +
    theme_minimal() +
    theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 9),
          axis.text.y = element_text(size = 7))
  p
}
# ── Example ──────────────────────────────────────────────────────
library(dplyr)
sp_means <- iris |> group_by(Species) |>
            summarise(across(where(is.numeric), mean)) |>
            column_to_rownames("Species")
plot_trait_heatmap(sp_means, scale = TRUE)