作爲從我已經創建的圖中刪除特定幾何的工作的一部分(我的鏈接here),我想動態確定ggplot2對象的每個圖層的幾何類型。如何確定一個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)
我不熟悉,我從原似乎documentation不工作(例如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
}
正如增加一個便利,您可以提供一個小的可重複數據集以及您的代碼? – Dason
哎呀,複製粘貼失敗。謝謝,@Dason –