我该如何以编程方式确定ggplot具有多少个facets?

19

以下是代码和图形。

这个图形有三个面。在the_plot中的哪里可以找到它有三个面?是的,我可以从mtcars数据框或the_plot$data中获得,但我不想重新创建数据分析。相反,我想检查the_plot的图形元素,这样我就不必在多个位置复制应用逻辑。the_plot$facet没有显示任何我认识的东西,其他绘图变量也是如此。

我正在使用tidyverse 1.3.0。

library(tidyverse)
data(mtcars)
the_plot<-ggplot(mtcars, aes(mpg, disp, group=cyl)) + facet_wrap(~cyl) + geom_point()
the_plot

多面图


可能从 https://dev59.com/HaHia4cB1Zd3GeqPbfAY 中提取 ggplot_build(the_plot)$layout$layout - MrFlick
请添加一些细节,你的 the_plot 不是你在图中看到的内容,而是你想要绘制的描述(数据、映射、主题等)。当你在控制台中写入 the_plot 时,实际上你正在调用 print(the_plot),这将启动一个过程,实现各种比例尺、分面的数量和位置等,并输出框、线和文本到一个图形设备。 - MrGumble
2个回答

13

您可以使用gg_build()函数访问ggplot数据

out <- ggplot_build(the_plot)

length(levels(out$data[[1]]$PANEL))
[1] 3


9

另一种方法

library(ggplot2)
data(mtcars)
the_plot<-ggplot(mtcars, aes(mpg, disp, group=cyl)) + facet_wrap(~cyl) + geom_point()
pb <- ggplot_build(the_plot)
pb$layout$layout$PANEL
#> [1] 1 2 3
#> Levels: 1 2 3

此代码片段由reprex软件包(v0.3.0)于2020-04-21创建。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接