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)
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?
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()
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With