【问题标题】:How can I programmatically tell how many facets a ggplot has?如何以编程方式判断 ggplot 有多少个方面?
【发布时间】:2020-04-21 23:35:10
【问题描述】:

下面是代码和图表。

该图具有三个方面。在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

【问题讨论】:

  • 可能是ggplot_build(the_plot)$layout$layout 来自stackoverflow.com/questions/44107119/…
  • 请添加一些细节,您的the_plot 不是您在图中看到的,而是您想要绘制的内容的描述(数据、映射、主题等)。当你在控制台写the_plot时,你实际上是在调用print(the_plot),它启动了一个过程,实现了分面的比例、数量和位置等,然后将框、线和文本输出到图形设备。跨度>

标签: r ggplot2


【解决方案1】:

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

out <- ggplot_build(the_plot)

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

【讨论】:

    【解决方案2】:

    另一种方法

    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 package (v0.3.0) 于 2020 年 4 月 21 日创建

    【讨论】:

      猜你喜欢
      • 2013-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 2014-07-04
      相关资源
      最近更新 更多