Skip to content

facet_grid can't deal with more than two facetting variables per margin #378

@fabian-s

Description

@fabian-s

Example:

d <- expand.grid(a=1:2, b=3:4, c=c(5:6, 5:6), d=7:8)
d$value <- rnorm(nrow(d))
d$x <- 1
ggplot(d, aes(x=x, y=value)) + geom_point() + facet_grid(a + b + c ~ d)
## throws an error
## stupid workaround:
d$bc <- with(d, factor(b):factor(c))
ggplot(d, aes(x=x, y=value)) + geom_point() + facet_grid(a + bc ~ d)

EDIT:

BrianDiggs has a good sugestion below, mine is overcomplicated.
There is also the simple workaround of simply doing:

facet_grid(list(c("a","b","c"), "d"))

Suggested solution:

the problem is the way that facet_grid defines the rows and cols simply as

   rows <- as.quoted(facets[[2]])

which breaks down for a formula with more than two terms.
Instead, I would suggest using a real formula parser to actually find all the terms, i.e.
use

    getVars <- function(frm){
       if(length(as.quoted(frm))==1) {
           if(as.character(frm)!="+"){
               return(as.quoted(frm))  
           } else return(NULL)
       } else {
           return(c(getVars(frm[[1]]), getVars(frm[[2]]), as.quoted(frm[[3]])))
       }    
    }

and replace lines

    rows <- as.quoted(facets[[2]])
    cols <- as.quoted(facets[[3]])

in facet_grid with

     rows <- getVars(facets[[2]])
     cols <- getVars(facets[[3]])

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions