hadley/ggplot2 — Issue #378: facet_grid can't deal with more than two facetting variables per margin
Author: fabian-s
Created: 2012-01-30 18:42:26+00:00
State: open

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)
```

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]])
````