Barplot of a functional diversity metric across sites or groups, with error bars and significance stars.
plot_fd_barplot <- function(fd_df, metric, group_col,
fill_col = "#2980b9", error = "se") {
library(ggplot2)
agg <- aggregate(fd_df[[metric]],
by = list(group = fd_df[[group_col]]),
FUN = function(x) c(mean = mean(x, na.rm=TRUE),
sd = sd(x, na.rm=TRUE),
n = length(x)))
df <- data.frame(group = agg$group,
mean = agg$x[,"mean"],
sd = agg$x[,"sd"],
n = agg$x[,"n"])
df$se <- df$sd / sqrt(df$n)
err <- if (error == "se") df$se else df$sd
ggplot(df, aes(group, mean)) +
geom_col(fill = fill_col, alpha = 0.85, width = 0.6) +
geom_errorbar(aes(ymin = mean - err, ymax = mean + err),
width = 0.2, linewidth = 0.6) +
labs(y = metric, x = NULL) +
theme_bw() +
theme(panel.grid.major.x = element_blank(),
panel.grid.minor = element_blank())
}
# ── Example ──────────────────────────────────────────────────────
# Use iris Sepal.Length as a "FD metric"
df <- data.frame(site = 1:150,
FRic = iris$Sepal.Length,
Species = iris$Species)
plot_fd_barplot(df, metric = "FRic", group_col = "Species")