Eri*_*lts 9 r layer ggplot2 proto ggproto
作为从我已经创建的绘图(此处为 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, is.null)]
ggplot2_object$layers <- layers
ggplot2_object
}
Run Code Online (Sandbox Code Playgroud)
ggplot 2.2更新: 如果你想要的是一个命名geom类型的字符串,你可以使用:
sapply(p$layers, function(x) class(x$geom)[1])
Run Code Online (Sandbox Code Playgroud)
它产生每个图层的geom对象的第一个类名.在OP的例子中:
[1] "GeomRibbon" "GeomLine"
Run Code Online (Sandbox Code Playgroud)
上面答案中的代码不再给出版本2.2显示的结果.接受的答案产生两个NULL值,另一个答案产生完整ggproto对象.
| 归档时间: |
|
| 查看次数: |
1024 次 |
| 最近记录: |