I'm trying to make new geoms and stats. I tried a StatChull code from this vignette. My goal is to manipulate an external parameter which is not an aesthetic value. Something like this:
stat_custom(data = df, mapping = aes(x = xval, y = val), myparam = myval, geom = "custom")
The thing is, when I make custom stat with compute_group()
, I can get the custom parameter. As soon as I change compute_group()
to compute_layer()
, program stops working.
Here is a working program for stat_chull():
StatChull <- ggproto("StatChull", Stat,
compute_group = function(self, data, scales, params, na.rm, myparam) {
message("My param has value ", myparam)
# browser()
data[chull(data$x, data$y), , drop = FALSE]
},
required_aes = c("x", "y")
)
stat_chull <- function(mapping = NULL, data = NULL, geom = "polygon",
position = "identity", na.rm = FALSE, myparam = "", show.legend = NA,
inherit.aes = TRUE, ...) {
layer(
stat = StatChull, data = data, mapping = mapping, geom = geom,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, myparam = myparam, ...)
)
}
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
stat_chull(fill = NA, colour = "black", myparam = "myval")
This prints on console:
My param has value myval
This programs errors when I change compute_group() to compute_layer():
StatChull <- ggproto("StatChull", Stat,
compute_layer = function(self, data, scales, params, na.rm, myparam) {
message("My param has value ", myparam)
# browser()
data[chull(data$x, data$y), , drop = FALSE]
},
required_aes = c("x", "y")
)
stat_chull <- function(mapping = NULL, data = NULL, geom = "polygon",
position = "identity", na.rm = FALSE, myparam = "", show.legend = NA,
inherit.aes = TRUE, ...) {
layer(
stat = StatChull, data = data, mapping = mapping, geom = geom,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, myparam = myparam, ...)
)
}
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
stat_chull(fill = NA, colour = "black", myparam = "myval")
This prints on console:
Warning: Ignoring unknown parameters: myparam
Error in message("My param has value ", myparam): argument "myparam" is missing, with no default
Can anyone tell me how do I access parameter values in compute_layer()
?