本文介绍了如何确定一个ggplot2对象的每个图层的几何类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为从我已经创建的情节中删除特定几何的努力的一部分(SO link ),我想动态地确定ggplot2对象每层的geom类型。



假设我不' t知道我添加图层的顺序,有没有办法动态查找具有特定几何图层的图层?如果我像下面一样打印图层,我可以看到图层存储在列表中,但我似乎无法访问geom类型。



<$ p $ (x = 1:3,y = 1:3,ymin = 0:2,ymax = 2:4)$ b(ggplot2)
dat $ bp p $ layers

[[1]]
映射: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())。






答案是w我能够想出一个动态移除图层的函数:

pre $ 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 .nu​​ll)]

ggplot2_object $ layers< - layers
ggplot2_object
}

$ b $
如果你想要的是一个命名geom类型的字符串,你可以使用下面的代码:

  sapply(p $ layers,function(x)class(x $ geom)[1])$ ​​b $ b  code> 

这会为每个图层的几何对象生成第一个类名称。在OP的例子中:

  [1]GeomRibbonGeomLine

上述答案中的代码不再给出2.2版本的结果。接受的答案产生两个NULL值,另一个答案产生完整的 ggproto 对象。


As part of an effort to remove a specific geom from a plot I've already created (SO link here), I'd like to dynamically determine the geom type of each layer of a ggplot2 object.

Assuming I don't know the order in which I added layers, is there a way to dynamically find layers with a specific geom? If I print out the layers like I do below I can see that the layers are stored in a list, but I can't seem to access the geom type.

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)

I'm not familiar with proto objects and things I've tried from the proto documentation don't seem to work (e.g. p$layers[[1]]$str()).


Thanks to the answers below I was able to come up with a function that removes a layer dynamically:

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
}
解决方案

ggplot 2.2 update:If what you want is a character string naming the geom type, you can use:

sapply(p$layers, function(x) class(x$geom)[1])

which yields the first class name for the geom object of each layer. In the OP's example:

[1] "GeomRibbon" "GeomLine" 

The code in the answers above no longer give the results shown for version 2.2 The accepted answer yields two NULL values, and the other answer yields full ggproto objects.

这篇关于如何确定一个ggplot2对象的每个图层的几何类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 21:29