操作ggproto得到多层

Manipulate ggproto to get multiple layers

我正在尝试从 ggproto 对象中获取多个区域图层。我不知道这是否可能,但如果是的话,我不知道该怎么做。

例如,我如何使用下面的代码生成两个区域层,其中一个的 y 坐标是另一个的一半 -

StatDensityHalf <- ggproto("StatDensity2", Stat, 
  required_aes = "x",
  default_aes = aes(y = ..density..),

  compute_group = function(data, scales, bandwidth = 1) {
    d <- density(data$x, bw = bandwidth)
    rbind(
       data.frame(x = d$x, density = d$y, fill = 1),
       data.frame(x = d$x, density = d$y/2, fill =2)
    )
  }  
)

stat_density_half <- function(mapping = NULL, data = NULL, geom = "line",
                                position = "identity", na.rm = FALSE, show.legend = NA, 
                                inherit.aes = TRUE, bandwidth = NULL,
                                ...) {
  layer(
    stat = StatDensityHalf, 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)) + 
  stat_density_half(bandwidth = 1, geom = "area", position = "stack")

请注意,我并不是在寻找一种解决方法来生成与示例所建议的相同的图。我正在寻找这个问题的通用解决方案。

好的,终于抽出时间来完成这个了。这将创建两层:

library(ggplot2)

StatDensityHalf <- 
    ggproto("StatDensity2", Stat,
            required_aes = "x",
            default_aes = aes(y = ..density..),
            compute_group = function(data, scales, bandwidth = 1,fak=1,fillgrp="1"){
                 d <- density(data$x, bw = bandwidth)
                data.frame(x = d$x, density = d$y / fak, fill = fillgrp)
             }
    )

stat_density_half <- function(mapping = NULL, data = NULL, geom = "line", 
                              position = "identity", na.rm = FALSE, show.legend = NA,
                              inherit.aes = TRUE, bandwidth = NULL, ...) {
    list(
      layer(
        stat = StatDensityHalf, data = data, mapping = mapping, geom = geom,
        position = position, show.legend = show.legend, inherit.aes = inherit.aes,
        params = list(bandwidth = bandwidth, na.rm = na.rm, fak = 1, fillgrp = "1", ...)),

      layer(
        stat = StatDensityHalf, data = data, mapping = mapping, geom = geom,
        position = position, show.legend = show.legend, inherit.aes = inherit.aes,
        params = list(bandwidth = bandwidth, na.rm = na.rm, fak = 2, fillgrp = "2", ...))
      )
    }

ggplot(mpg, aes(cty)) +
  stat_density_half(bandwidth = 2, geom = "area", position = "stack") +
  scale_fill_manual(values = c("2" = "red", "1" = "blue"))

产量:

更新:

在第一次迭代中我有两个 ggproto,因为我没有真正看到如何将参数添加到 ggproto(这里是 fakfillgrp ).解决方案是除了将它们添加到 params 列表之外,还明确地将它们添加到 compute_group 函数中,否则 ggproto 包装器会抱怨并失败。