我正在尝试制作新的几何图形和统计数据。我从这个小插图中尝试了一个 StatChull 代码。我的目标是操纵一个不是美学价值的外部参数。像这样的东西:
stat_custom(data = df, mapping = aes(x = xval, y = val), myparam = myval, geom = "custom")
问题是,当我使用 进行自定义统计时compute_group()
,我可以获得自定义参数。一旦我更改compute_group()
为compute_layer()
,程序就会停止工作。
这是 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")
这在控制台上打印:
My param has value myval
当我将compute_group()更改为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")
这在控制台上打印:
Warning: Ignoring unknown parameters: myparam
Error in message("My param has value ", myparam): argument "myparam" is missing, with no default
谁能告诉我如何访问参数值compute_layer()
?