Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract number of rows from faceted ggplot

Tags:

r

ggplot2

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,3), rep(5,3), rep(6,3), rep(7,3)))

p <- ggplot2::ggplot(plotdf) + 
     ggplot2::geom_point(ggplot2::aes(x=x,y=y)) + 
     ggplot2::facet_wrap(~ z)

enter image description here

How to extract the number of rows (or cols) from p?

p$facet seems to contain relevant info:

p$facet
    <ggproto object: Class FacetWrap, Facet>
        compute_layout: function
        draw_back: function
        draw_front: function
        draw_labels: function
        draw_panels: function
        finish_data: function
        init_scales: function
        map: function
        map_data: function
        params: list
        render_back: function
        render_front: function
        render_panels: function
        setup_data: function
        setup_params: function
        shrink: TRUE
        train: function
        train_positions: function
        train_scales: function
        super:  <ggproto object: Class FacetWrap, Facet>

But I can't manage to extract nrow or ncol from it. Any suggestions?

like image 779
Aditya Avatar asked Dec 13 '22 23:12

Aditya


2 Answers

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()
}
like image 128
balin Avatar answered Jan 06 '23 06:01

balin


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
like image 24
Axeman Avatar answered Jan 06 '23 06:01

Axeman