Don't rely on the default ordering of levels imposed by factor()
or internally by ggplot
if the grouping variable you supply is not a factor. Set the levels explicitly yourself.
dat <- data.frame(x = runif(100), y = runif(100),
Group = gl(5, 20, labels = LETTERS[1:5]))
head(dat)
with(dat, levels(Group))
What if I want them in this arbitrary order?
set.seed(1)
with(dat, sample(levels(Group)))
To do this, set the levels the way you want them.
set.seed(1) # reset the seed so I get the random order form above
dat <- within(dat, Group <- factor(Group, levels = sample(levels(Group))))
with(dat, levels(Group))
Now we can use this to have the panels drawn in the order we want:
require(ggplot2)
p <- ggplot(dat, aes(x = x)) + geom_bar()
p + facet_wrap( ~ Group)
Which produces:
relevel()
orreorder()
or make a custom order and usefactor()
. – Chase