首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >操作ggproto以获得多个层

操作ggproto以获得多个层
EN

Stack Overflow用户
提问于 2016-01-24 16:01:45
回答 1查看 581关注 0票数 4

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

例如,如何让下面的代码生成两个区域层,其中一个有y坐标作为另一个区域的一半-

代码语言:javascript
复制
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")

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-24 19:29:30

好吧,终于有时间完成这件事了。这就创建了两个层:

代码语言:javascript
复制
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),解决方案是将它们显式地添加到compute_group函数中,并将它们添加到params列表中,否则ggproto包装器会出现故障。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34977946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档