Find the density value at a given cumulative probability threshold from a KDE grid.
density_threshold <- function(z, p) { dx <- sort(as.vector(z), decreasing = TRUE) cs <- cumsum(dx) / sum(dx) dx[which(cs >= p)[1]] }