如何以编程方式告诉 ggplot 有多少个方面?

dfr*_*kow 16 r ggplot2

下面是代码和图表。

该图具有三个方面。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
Run Code Online (Sandbox Code Playgroud)

分面图

use*_*545 12

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

out <- ggplot_build(the_plot)

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

Run Code Online (Sandbox Code Playgroud)


小智 8

另一种方法

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
Run Code Online (Sandbox Code Playgroud)

reprex 包(v0.3.0)于 2020 年 4 月 21 日创建