这是后续this https://stackoverflow.com/questions/57072096/passing-an-extra-parameter-to-a-custom-geom-in-ggplot2问题。我正在尝试使用自定义参数编写自己的几何图形。我的问题是如何使用省略号(...)来传递额外的参数。
以下示例代码按预期工作:
draw_panel_func <- function(data, panel_params, coord, showpoints=FALSE) {
print(showpoints)
if(showpoints) {
coords <- coord$transform(data, panel_params)
grid::pointsGrob(coords$x, coords$y)
} else {
zeroGrob()
}
}
## definition of the new geom. setup_data inserts the parameter
## into data, therefore making it accessible for .draw_panel_func
GeomSimplePoint <- ggproto("GeomSimplePoint", Geom,
required_aes = c("x", "y"),
default_aes = aes(shape = 19, colour = "black"),
draw_key = draw_key_point,
extra_params = c("na.rm", "showpoints"),
draw_panel = draw_panel_func
)
geom_simple_point <- function(mapping = NULL, data = NULL, stat = "identity",
position = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, showpoints=TRUE, ...) {
layer(
geom = GeomSimplePoint, mapping = mapping, data = data, stat = stat,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, showpoints=showpoints, ...)
)
}
这有效,我可以打电话
ggplot(mpg, aes(displ, hwy)) + geom_simple_point(showpoints=FALSE)
省略点的绘制。
但是,因为我想对不同的新几何对象使用通用函数,所以我更愿意定义draw_panel
函数没有显式命名 showpoints 参数,而是使用省略号。我尝试了以下操作(所有其余代码保持不变),它不起作用:
draw_panel_func <- function(data, panel_params, coord, ...) {
showpoints <- list(...)$showpoints
if(showpoints) {
coords <- coord$transform(data, panel_params)
grid::pointsGrob(coords$x, coords$y)
} else {
zeroGrob()
}
}
返回的错误是:
if (showpoints) { 中的错误:参数长度为零
当我执行以下操作时,会发生一件有趣的事情:
draw_panel_func <- function(data, panel_params, coord, showpoints=FALSE, ...) {
#showpoints <- list(...)$showpoints
if(showpoints) {
coords <- coord$transform(data, panel_params)
grid::pointsGrob(coords$x, coords$y)
} else {
zeroGrob()
}
}
由于某种原因,showpoints 现在始终为 FALSE。但是,那...
列表为空。这完全出乎意料。
这一切都非常令人困惑,并且肯定它的表现并不像我预期的那样。在这种情况下可以使用省略号吗?如果是,那么如何?这里发生了什么?
EDIT:按照 Gilean0709 的建议我尝试删除showpoints
从定义geom_simple_point
:
geom_simple_point <- function(mapping = NULL, data = NULL, stat = "identity",
position = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, ...) {
layer(
geom = GeomSimplePoint, mapping = mapping, data = data, stat = stat,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
这仍然给出相同的错误(showpoints 为 NULL)。