从ggplot2对象

时间:2016-10-07 13:06:02

标签: r ggplot2

在ggplot输出中,是否有一个包含特定于图层的对象的对象?我只能找到默认值(我不想使用ggplot_build,我想在对象本身找到它)

p=ggplot(iris,aes(x =Sepal.Length,y=Sepal.Width))+geom_point(alpha=.5,colour='blue')+geom_line()

>p$layers[[1]]$geom$default_aes
* shape  -> 19
* colour -> "black"
* size   -> 1.5
* fill   -> NA
* alpha  -> NA
* stroke -> 0.5

>p$layers[[2]]$geom$default_aes
* colour   -> "black"
* size     -> 0.5
* linetype -> NA
* alpha    -> NA

1 个答案:

答案 0 :(得分:1)

fetch_layer_aes=function (self, data=data.frame(x=1), params = list()){
   missing_aes <- setdiff(names(self$default_aes), names(data))
if (ggplot2:::empty(data)) {
  data <- plyr::quickdf(self$default_aes[missing_aes])
}
else {
  data[missing_aes] <- self$default_aes[missing_aes]
}
aes_params <- intersect(self$aesthetics(), names(params))
ggplot2:::check_aesthetics(params[aes_params], nrow(data))
data[aes_params] <- params[aes_params]
data[,-1]
}

>lapply(p$layers,function(x) fetch_layer_aes(self=x$geom,params=x$aes_params))
[[1]]
    shape colour size fill alpha stroke
1    19   blue  1.5   NA   0.5    0.5

[[2]]
  colour size linetype alpha
1  black  0.5        1    NA