简体   繁体   English

geom_density-自定义KDE

[英]geom_density - customize KDE

I would like to use a different KDE method than stats::density which is used by stat_density / geom_density to plot a KDE for a distrubtion. 我想使用与stats::density不同的KDE方法, stat_density / geom_density使用geom_density来绘制KDE进行扰动。 How should I go about this? 我应该怎么做?

I realized that this can be done by extending ggplot2 with ggproto . 我意识到可以通过用ggproto扩展ggplot2来完成。 The ggproto vignette has an example that can be adapted pretty easily: ggproto 小插图有一个可以很容易地修改的示例:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM