我正在创建一个自定义几何图形,并希望它采用一个额外的参数,称为showpoints
,它对实际绘图执行某些操作。例如,通过将其设置为 FALSE,geom 实际上会返回一个zeroGrob()
. 我找到了一种方法,但是(i)它笨重而且有些奇怪,并且(ii)我不完全理解我在做什么,这是一个不好的迹象。问题是,当你定义一个新的统计数据时,可以运行setup_params
,但 geoms 没有它:
与 Stat 和 Position 相比,Geom 有点不同,因为设置和计算函数的执行是分开的。setup_data 在位置调整之前运行,而 draw_layer 直到渲染时间才运行,很晚。这意味着没有 setup_params 因为很难传达更改。
基本上,我的代码可以使用附加参数来抑制点的绘制:
# draw the points by default
ggplot(mpg, aes(displ, hwy)) + geom_simple_point()
# suppresses drawing of the points
ggplot(mpg, aes(displ, hwy)) + geom_simple_point(showpoints=FALSE)
到目前为止,这是我的代码,基于扩展 ggplot2 教程:
## Return the grob to draw. The additional parameter,
## showpoints, determines whether a points grob should be returned,
## or whether zeroGrob() should take care of not showing the points
.draw_panel_func <- function(data, panel_params, coord) {
coords <- coord$transform(data, panel_params)
showpoints <- unique(data$showpoints)
cat("showpoints=", as.character(showpoints), "\n")
if(!is.null(showpoints) && is.logical(showpoints) && !showpoints) {
return(zeroGrob())
} else {
return(
grid::pointsGrob(coords$x, coords$y,
pch = coords$shape,
gp = grid::gpar(col = coords$colour))
)
}
}
## 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,
setup_data = function(data, params) {
if(!is.null(params$showpoints)) {
data$showpoints <- params$showpoints
}
data
},
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, ...)
)
}
有没有更简单的方法将选择的额外参数传递给geom?如果我可以定义extra_params
,为什么我不能以某种方式更轻松地访问它们?