[R] Still struggling with facet_grid_paginate() from package ggforce.

Rolf Turner r@turner @end|ng |rom @uck|@nd@@c@nz
Mon Dec 2 01:45:00 CET 2019


On 2/12/19 10:45 am, Rui Barradas wrote:

> Hello,
> 
> Here are two ways.
> 
> The first is an adaptation from your code. It uses facet_wrap_paginate, 
> not *_grid_*.
> 
> 
> plotObj2 <- vector("list",2)
> for(pg in 1:2) {
>    plotObj2[[pg]] <- ggplot(egDat) +
>      geom_point(aes(y = obsd, x = x),
>                 na.rm = TRUE, shape = 20, colour = "blue") +
>      geom_line(aes(y = fit2, x = cPred)) +
>      facet_wrap_paginate(facets = ~Trt,
>                          ncol = 4, nrow = 3, page = pg) +
>      theme_bw()
> }
> print(plotObj2)
> 
> 
> The second is an adaptation of SO[1]. It needs two calls to the plot 
> code and it's slower but gets the job done.
> 
> 
> g <- ggplot(egDat) +
>    geom_point(aes(y = obsd, x = x),
>               na.rm = TRUE, shape = 20, colour = "blue") +
>    geom_line(aes(y = fit2, x = cPred)) +
>    facet_wrap_paginate(facets = ~Trt, ncol = 4, nrow = 3, page = 1) +
>    theme_bw()
> 
> n <- n_pages(g)
> for(i in 1:n){
>    print(g + facet_wrap_paginate(~Trt, ncol = 4, nrow = 3, page = i))
> }
> 
> print(g)
> 
> 
> 
> Hope this helps.

Indeed it did.  You are brilliant, Rui. Problem solved.

I note that one can, I think, calculate the number of pages a priori,
thus avoiding two calls to ggplot(), in something like the following manner:

nface <- with(Dat,prod(sapply(condVars,
                        function(x){length(levels(get(x)))})))

npgs  <- ceiling(nface/(nrow*ncol))

where Dat is the data frame of data being plotted and condVars is a 
vector of the names of the variables being conditioned on (i.e. the 
variables determining the facets).  In the example that I provided,
condVars would just be "Trt", but it all seems to work in settings in 
which there is more than one conditioning variable.

Thanks very much.

cheers,

Rolf

-- 
Honorary Research Fellow
Department of Statistics
University of Auckland
Phone: +64-9-373-7599 ext. 88276



More information about the R-help mailing list