0

I have a data frame that looks like this

df <- data.frame(id=rep(c(1,5,2,6,4,3), each=5),
                 group=rep(c(1,2,2,2,1,1), each=5),
                 var1=runif(30))

I now want to plot var1 using ggplot and facet the plot by id, but sort the facets by group (and by id within group). I gather that I have to make id a factor with levels that sort neatly by group but I cannot figure out how to accomplish this elegantly.

RoyalTS
  • 9,545
  • 12
  • 60
  • 101
  • 2
    Search for something along the lines of "sorting factor levels". This question has been addressed before. – Roman Luštrik Jan 24 '14 at 13:34
  • See [this](http://trinkerrstuff.wordpress.com/2012/10/15/how-do-i-re-arrange-ordering-a-plot/) and [this](http://trinkerrstuff.wordpress.com/2013/08/14/how-do-i-re-arrange-ordering-a-plot-revisited/?relatedposts_exclude=527) – Tyler Rinker Jan 24 '14 at 14:00

1 Answers1

1
# sort by group and id
df_sorted <- df[with(df, order(group, id)), ]
# reorder factor levels
df_sorted$id <- factor(df_sorted$id, levels=unique(df_sorted$id))
# plot something
ggplot(df_sorted, aes(var1)) + facet_wrap(~id) + geom_density()

enter image description here

tonytonov
  • 25,060
  • 16
  • 82
  • 98