compute_kde(scores, n_grid, lims, thresholds, ...)

Kernel density estimation on PCA scores with multiple threshold contours.

functional diversityvisualisation
Args:scores — PCA score matrixn_grid — grid resolutionlims — axis limitsthresholds=c(0.5,0.99)
compute_kde <- function(scores, n_grid, lims, thresholds = c(0.5, 0.99),
                        bw_mult = 1) {
  # Bandwidth par défaut de kde2d, réduit par bw_mult
  h <- c(MASS::bandwidth.nrd(scores[, 1]),
         MASS::bandwidth.nrd(scores[, 2])) * bw_mult
  kd <- MASS::kde2d(scores[, 1], scores[, 2],
                    n = n_grid, lims = lims, h = h)
  df <- expand.grid(PC1 = kd$x, PC2 = kd$y)
  df$z <- as.vector(kd$z)
  thr <- sapply(thresholds, function(p) density_threshold(kd$z, p))
  names(thr) <- as.character(thresholds)
  list(kd = kd, df = df, thr = thr)
}