作为从我已经创建的绘图(此处为 SO链接)中删除特定geom的努力的一部分,我想动态确定ggplot2对象的每个层的geom类型.
假设我不知道添加图层的顺序,有没有办法动态查找具有特定geom的图层?如果我像下面那样打印出图层,我可以看到图层存储在列表中,但我似乎无法访问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)
Run Code Online (Sandbox Code Playgroud)
我不熟悉原型对象,我从原型文档中尝试的东西似乎不起作用(例如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, …Run Code Online (Sandbox Code Playgroud)