I'm trying to get multiple area layers out of a ggproto
object. I don't know if this is even possible but in case it is, I'm unable to figure out how.
For instance, how can I get the code below to produce two area layers where one has y coordinates as half of the other -
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")
Please note, I'm NOT looking for a workaround to produce the same plot as the example suggests. I'm looking for a generic solution to this problem.