geom_density - 自定义 KDE

geom_density - customize KDE

我想使用不同于 stats::density 的 KDE 方法,后者被 stat_density/geom_density 用于绘制 KDE 以进行分发。我该怎么办?

我意识到这可以通过用 ggproto 扩展 ggplot2 来完成。 ggproto vignette 有一个可以很容易改编的例子:

StatDensityCommon <- ggproto("StatDensityCommon", Stat, 
  required_aes = "x",

  setup_params = function(data, params) {
    if (!is.null(params$bandwidth))
      return(params)

    xs <- split(data$x, data$group)
    bws <- vapply(xs, bw.nrd0, numeric(1))
    bw <- mean(bws)
    message("Picking bandwidth of ", signif(bw, 3))

    params$bandwidth <- bw
    params
  },

  compute_group = function(data, scales, bandwidth = 1) {
    ### CUSTOM FUNCTION HERE ###
    d <- locfit::density.lf(data$x)  #FOR EXAMPLE
    data.frame(x = d$x, y = d$y)
  }  
)

stat_density_common <- function(mapping = NULL, data = NULL, geom = "line",
                                position = "identity", na.rm = FALSE, show.legend = NA, 
                                inherit.aes = TRUE, bandwidth = NULL,
                                ...) {
  layer(
    stat = StatDensityCommon, data = data, mapping = mapping, geom = geom, 
    position = position, show.legend = show.legend, inherit.aes = inherit.aes,
    params = list(bandwidth = bandwidth, na.rm = na.rm, ...)
  )
}

ggplot(mpg, aes(displ, colour = drv)) + stat_density_common()