[R] Order of factors with facets in ggplot2

Ista Zahn istazahn at gmail.com
Sat Oct 12 21:23:37 CEST 2013


On Sat, Oct 12, 2013 at 12:01 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.

I think this is impossible if you keep your data in a single
data.frame, because there can only be one order of the factor levels.
You may have to split it out into separate data.frames, like this:

df.1 <- subset(df, f1 == "A")
df.2 <- subset(df, f1 == "B")

df.1$f2 <- reorder(df.1$f2, df.1$Avg_x)
df.2$f2 <- reorder(df.2$f2, df.2$Avg_x)

ggplot(mapping = aes(x=f2, y=x)) +
    geom_boxplot(data=df.1) +
    geom_boxplot(data=df.2) +
    stat_summary(data = df.1, fun.y=mean, geom="point", col = "red") +
    stat_summary(data = df.2, fun.y=mean, geom="point", col = "red") +
    facet_wrap(~ f1, scale = "free", ncol = 1)

Best,
Ista

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