我试图从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")请注意,我并不是在寻找解决办法来产生与示例所建议的相同的情节。我正在寻找这个问题的通用解决方案。
发布于 2016-01-24 19:29:30
好吧,终于有时间完成这件事了。这就创建了两个层:
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 (这里是fak和fillgrp),解决方案是将它们显式地添加到compute_group函数中,并将它们添加到params列表中,否则ggproto包装器会出现故障。
https://stackoverflow.com/questions/34977946
复制相似问题