【问题标题】:geom_density - customize KDEgeom_density - 自定义 KDE
【发布时间】:2016-03-07 07:27:42
【问题描述】:

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

【问题讨论】:

    标签: r ggplot2 kernel-density


    【解决方案1】:

    我意识到这可以通过将ggplot2 扩展为ggproto 来完成。 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()
    

    【讨论】:

    • 感谢您的贡献。是否可以使用 np 输出(例如可变核密度)作为 ggplot 的输入?
    猜你喜欢
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    相关资源
    最近更新 更多