Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically tell how many facets a ggplot has?

Tags:

r

ggplot2

Below is code and a graph.

The graph has three facets. Where in the_plot can I find it has three facets? Yes, I could get that from the mtcars data frame, or the_plot$data, but I don't want to recreate the data analysis. Rather, I want to inspect the graphical elements of the_plot, so I don't have to duplicate application logic in multiple places. the_plot$facet doesn't show anything I recognize, nor do the other plot variables.

I'm using tidyverse 1.3.0.

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

faceted plot

like image 293
dfrankow Avatar asked Apr 21 '20 15:04

dfrankow


People also ask

What are facets in Ggplot?

The facet approach partitions a plot into a matrix of panels. Each panel shows a different subset of the data. This R tutorial describes how to split a graph using ggplot2 package. There are two main functions for faceting : facet_grid()

What does Facet_grid do in R?

facet_grid() forms a matrix of panels defined by row and column faceting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data.

What is a facet wrap in R?

facet_wrap() makes a long ribbon of panels (generated by any number of variables) and wraps it into 2d. This is useful if you have a single variable with many levels and want to arrange the plots in a more space efficient manner. You can control how the ribbon is wrapped into a grid with ncol , nrow , as.


Video Answer


2 Answers

you can access the ggplot data with the gg_build() - function

out <- ggplot_build(the_plot)

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

like image 195
user12256545 Avatar answered Oct 19 '22 08:10

user12256545


Another method

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

Created on 2020-04-21 by the reprex package (v0.3.0)

like image 36
yang Avatar answered Oct 19 '22 10:10

yang