作为从我已经创建的绘图中删除特定几何图形的一部分(此处链接),我想动态确定 ggplot2 对象的每一层的几何图形类型。
假设我不知道添加图层的顺序,有没有办法动态查找具有特定几何图形的图层?如果我像下面那样打印出图层,我可以看到这些图层存储在一个列表中,但我似乎无法访问 geom 类型。
library(ggplot2)
dat <- data.frame(x=1:3, y=1:3, ymin=0:2, ymax=2:4)
p <- ggplot(dat, aes(x=x, y=y)) + geom_ribbon(aes(ymin=ymin, ymax=ymax), alpha=0.3) + geom_line()
p$layers
[[1]]
mapping: ymin = ymin, ymax = ymax
geom_ribbon: na.rm = FALSE, alpha = 0.3
stat_identity:
position_identity: (width = NULL, height = NULL)
[[2]]
geom_line:
stat_identity:
position_identity: (width = NULL, height = NULL)
我不熟悉 proto 对象,而且我从 proto文档中尝试过的东西似乎不起作用(例如p$layers[[1]]$str()
)。
感谢下面的答案,我能够想出一个动态删除图层的函数:
remove_geom <- function(ggplot2_object, geom_type) {
layers <- lapply(ggplot2_object$layers, function(x) if(x$geom$objname == geom_type) NULL else x)
layers <- layers[!sapply(layers, is.null)]
ggplot2_object$layers <- layers
ggplot2_object
}