すでに作成したプロットから特定のgeomを削除する取り組みの一環として(SOリンクはこちら)、ggplot2オブジェクトの各レイヤーの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)
私はプロトオブジェクトに精通しておらず、プロトドキュメントから試したことがうまくいかないようです(例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
}