Consider a faceted ggplot
plotdf <- data.frame(x = 1:21,
y = 3*(1:21)+4,
z = c(rep(1,3), rep(2,3), rep(3,3), rep(4
If you don't define the number of rows or columns manually, this is calculated for you with wrap_dims
.
So, in your example:
n_panels <- length(unique(ggplot_build(p)$data[[1]]$PANEL))
wrap_dims(n_panels)
[1] 3 3
To take into account any manual definitions as well, we can look up those parameters too, e.g. ggplot_build(p)$layout$facet$params$nrow
gives the number of rows.
A function then to get the number of rows and columns:
get_row_col <- function(p) {
n <- length(unique(ggplot_build(p)$data[[1]]$PANEL))
par <- ggplot_build(p)$layout$facet$params
wrap_dims(n, par$nrow, par$ncol)
}
> get_row_col(p) [1] 3 3
gg_facet_nrow <- function(p){
assertive.types::assert_is_any_of(p, 'ggplot')
p %>% ggplot2::ggplot_build() %>%
magrittr::extract2('layout') %>%
magrittr::extract2('panel_layout') %>%
magrittr::extract2('ROW') %>%
unique() %>%
length()
}
gg_facet_nrow(p)
Following up on @Aditya's answer, this is (as of ggplot 3.1.1):
library(magrittr)
gg_facet_nrow_ng <- function(p){
assertive.types::assert_is_any_of(p, 'ggplot')
p %>%
ggplot2::ggplot_build() %>%
magrittr::extract2('layout') %>%
magrittr::extract2('layout') %>%
magrittr::extract2('ROW') %>%
unique() %>%
length()
}