r - Manipulate ggproto to get multiple layers -


i'm trying multiple area layers out of ggproto object. don't know if possible in case is, i'm unable figure out how.

for instance, how can code below produce 2 area layers 1 has y coordinates half of 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 workaround produce same plot example suggests. i'm looking generic solution problem.

okay, got around finishing up. creates 2 layers:

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

yields:

enter image description here

update:

in first iteration had 2 ggproto's because didn't see how add parameters ggproto (here fak , fillgrp). solution add them explicitly compute_group function in addition adding them params list, otherwise ggproto wrapper complains , fails.


Comments