hadley/ggplot2 — pull request #613 by wch (2012-07-08 21:40:40+00:00)
Title: Correct order of facets when adding layers. Fixes #543

This fixes #543. The reason this works is because a call to `ldply()` in `layout_base()`:

```R
base <- unique(ldply(values[has_all]))
```

If the first data frame in the list contains all the levels of the variable, then `base` will have that ordering of the variables. However, if the first data frame does *not* contain all the levels, then `base` will add the levels in the order they're encountered.

To illustrate:

```R
d1 <- data.frame(f=factor(rep(letters[1:3], each=5), levels=letters[3:1]))
d2 <- data.frame(f=rep("b", 15))

str(d1)
# 'data.frame': 15 obs. of 1 variable:
# $ f: Factor w/ 3 levels "c","b","a": 3 3 3 3 3 2 2 2 2 2 ...
str(d2)
# 'data.frame': 15 obs. of 1 variable:
# $ f: Factor w/ 1 level "b": 1 1 1 1 1 1 1 1 1 1 ...

str(unique(ldply(list(d1, d2))))
# 'data.frame': 3 obs. of 1 variable:
# $ f: Factor w/ 3 levels "c","b","a": 3 2 1
str(unique(ldply(list(d2, d1))))
# 'data.frame': 3 obs. of 1 variable:
# $ f: Factor w/ 3 levels "b","c","a": 1 3 2
```

The fix is to put the default data frame from the ggplot object first, rather than last.