操纵ggproto以获得多个图层

时间:2016-01-24 16:01:45

标签: r ggplot2 ggproto

我试图从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")

请注意,我并不是在寻找一种解决方法来制作与示例所示相同的情节。我正在寻找这个问题的通用解决方案。

1 个答案:

答案 0 :(得分:3)

好的,终于到处完成了这个。这会创建两个层:

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

收率:

enter image description here

更新

在第一次迭代中,我有两个ggproto因为我没有真正看到如何将参数添加到ggproto(此处为fakfillgrp)。解决方案是将它们显式添加到compute_group函数中,并将它们添加到params列表中,否则ggproto包装器会抱怨并失败。