Hello,


I'd like to produce a ggplot where the order of factors within facets is
based on the average of another variable.


Here's a reproducible example. My problem is that the factors are ordered
similarly in both facets. I would like to have, within each facet of `f1',
boxplots for 'x' within each factor `f2', where the boxplots are ordered
based on the average of x within each facet.


So in this case, for facet A: the order should be M4, M1, M3, M2; and for
facet B: M4, M2, M1, M3


library(ggplot2)

library(plyr)


set.seed(1)

f1 <- sample(c("A", "B"), 100, replace= T)

f2 <- gl(4, 25, labels = paste("M", 1:4, sep=""))

x <- runif(100)

df <- data.frame(f1, f2, x)

#df <- df[order(df[,1]), ]

df <- ddply(df, ~ f1 + f2, transform, Avg_x = mean(x))


myplot <- ggplot(df, aes(x=reorder(f2, Avg_x), x)) + geom_boxplot() +

  facet_wrap(~ f1, scale = "free", ncol = 1) +

  stat_summary(fun.y=mean, geom="point", col = "red")

myplot


Thanks in advance for any help!

Lars.

	[[alternative HTML version deleted]]

