Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can extract the number of facets of your plot with the following function. I have tried to be as general as possible and it should be applicable for both <code>facet_grid</code> and <code>facet_wrap</code> faceting. It is however possible that I have overlooked some possibilities. If so, please leave a comment. </p> <pre><code>nfacetcols &lt;- function(p) { if (is.null(p$facet$cols) &amp; is.null(p$facet$facets)) return(1) # facet_grid - version if (! is.null(p$facet$cols)) { if (length(p$facet$cols)==0) return(1) dat &lt;- p$data[,as.character(p$facet$cols)] if (is.factor(dat)) return(nlevels(dat)) if (is.data.frame(dat)) return(nrow(unique(dat))) if (is.numeric(dat)) return(length(unique(dat))) } # facet_wrap - version if (! is.null(p$facet$facets)){ if (!is.null(p$facet$ncol)) return(p$facet$ncol) dat &lt;- p$data[,as.character(p$facet$facets)] tot &lt;- ifelse(is.factor(dat), nlevels(dat), nrow(unique(dat))) if (!is.null(p$facet$nrow)) return(ceiling(tot/p$facet$nrow)) return(ceiling(sqrt(tot))) } } </code></pre> <p>With this function, you can extract the number of columns. The number of levels of your <code>x</code>-factor can easily be extracted using </p> <pre><code>xlvls &lt;- nlevels(p$data[,p$labels$x]) </code></pre> <p>Then using the suggestion of @agstudy, you can use the following code to <code>ggsave</code> your plot: </p> <pre><code># create data set set.seed(123) N &lt;- 20 df &lt;- data.frame(a = sample(LETTERS[1:10], N, replace=TRUE), b = sample(letters[1:5], N, replace=TRUE), yax = rnorm(N), xax = factor(sample(letters[16:20], N, replace=TRUE))) # plot p &lt;- ggplot(df, aes(xax, yax)) + geom_point() + facet_grid(b~a) ggsave("eg.plot.png", p + theme(axis.text.x = element_text(angle = 90, hjust = 1)), width=xlvls*nfacetcols(p)/5) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload