有没有办法从ggplot_build()(或任何其他功能)搜索整个输出,几乎像搜索文件夹的每个子目录的完整内容?
细节:
我正在寻找一个解决方案来检索ggplot2_3.0.0中轴标签的值,其中一个早期答案显示,根据ggplot2版本,正确的答案很可能包含部分$layout和/或$x.labels输出ggplot_build(g).所以我开始检查ggplot_build()输出的每一步.其中一个步骤看起来像下面的输出.
小片1:
ggplot_build(g)$layout
Run Code Online (Sandbox Code Playgroud)
输出1:
<ggproto object: Class Layout, gg>
coord: <ggproto object: Class CoordCartesian, Coord, gg>
aspect: function
clip: on
[...]
map_position: function
panel_params: list
panel_scales_x: list
panel_scales_y: list
render: function
[...]
ylabel: function
super: <ggproto object: Class Layout, gg>
>
Run Code Online (Sandbox Code Playgroud)
在那里,在下面panel params,x.labels可以找到许多有用的信息,如下所示:
摘录2:
ggplot_build(g)$layout$panel_params
Run Code Online (Sandbox Code Playgroud)
输出2:
[[1]]
[[1]]$`x.range`
[1] 7.7 36.3
[[1]]$x.labels
[1] "10" "15" "20" "25" "30" "35"
[[1]]$x.major
[1] 0.08041958 0.25524476 0.43006993 0.60489510 0.77972028 0.95454545
Run Code Online (Sandbox Code Playgroud)
它可以像这样直接引用:
代码段3:
ggplot_build(g)$layout$panel_params[[1]]$x.labels
Run Code Online (Sandbox Code Playgroud)
输出3:
[1] "10" "15" "20" "25" "30" "35"
Run Code Online (Sandbox Code Playgroud)
我试图采用更优雅的方法:
我确信我可以做到这一点capture.output()就像你可以与str()所描述的在这里,但据我所知,你不会发现x.labels有两种.我不会用这个输出充满问题,因为它大约有300行.
谢谢你的任何建议!
此函数遍历嵌套列表结构,并通过该结构查找包含给定字符串的路径:
find_name <- function(obj, name) {
# get all named paths through obj
find_paths <- function(obj, path) {
if ((!is.list(obj) && is.null(names(obj))) || identical(obj, .GlobalEnv)) {
return (path)
} else {
if (is.null(names(obj))) {
return(c(path,
lapply(seq_along(obj), function(x) find_paths(obj[[x]], paste0(path, "[[", x, "]]")))
))
} else {
return(c(path,
lapply(names(obj), function(x) find_paths(obj[[x]], paste(path, x, sep = "$")))
))
}
}
}
# get all the paths through the nested structure
all_paths <- unlist(find_paths(obj, deparse(substitute(obj))))
# find the requested name
path_to_name <- grep(paste0("\\$", name, "$"), all_paths, value = TRUE)
return (path_to_name)
}
Run Code Online (Sandbox Code Playgroud)
以下是将此函数与ggplot_built对象一起使用的示例:
library(ggplot2)
p <- ggplot(mtcars) + geom_point(aes(x = disp, y = mpg, col = as.factor(cyl)))
gb <- ggplot_build(p)
find_name(gb, "x.labels")
## [1] "gb$layout$panel_params[[1]]$x.labels"
Run Code Online (Sandbox Code Playgroud)
也可以直接获取内容x.labels:
eval(parse(text = find_name(gb, "x.labels")))
## [1] "100" "200" "300" "400"
Run Code Online (Sandbox Code Playgroud)
关于它是如何工作的一些评论:
find_paths()遍历嵌套结构并以类似于 的形式返回通过该结构的所有“路径” "gb$layout$panel_params[[1]]$x.labels"。FALSEforis.list()和环境。必须处理所有这些情况。ggplot_built包含对全局环境 ( gb$layout$facet_params$plot_env)的引用,如果处理不当会导致无限循环。find_paths()是一个嵌套列表,但结构可以很容易地用 简化unlist()。find_name(gb, "x")不会返回"gb$layout$panel_params[[1]]$x.labels"。我已经使用ggplot_built示例中的对象和嵌套列表测试了该函数。我不能保证它适用于所有情况。