[R] Order of factors with facets in ggplot2
arun
smartpink111 at yahoo.com
Sat Oct 12 22:23:24 CEST 2013
Hi,
As you using library(plyr), you may try:
library(ggplot2)
library(plyr)
df2 <- df
d1 <- dlply(df2,.(f1),function(u) {
u$f2<- reorder(u$f2,u$Avg_x)
ggplot(mapping=aes(x=f2,y=x))+
geom_boxplot(data=u)+stat_summary(data=u,fun.y=mean,geom="point",col="red")+
facet_wrap(~f1,scale="free",ncol=1)})
library(gridExtra)
grid.arrange(d1$A,d1$B,nrow=2)
# grid.arrange(d1$A,d1$B,nrow=2,main=textGrob("Facet grouping",gp=gpar(fontsize=15,font=1)))
A.K.
On Saturday, October 12, 2013 12:03 PM, Lars Bishop <lars52r at gmail.com> wrote:
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]]
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list