Search code examples
rggplot2facet-wrap

Reordering ggplot facet_wrap by group as columns


I am trying to plot a cluster by individuals (6x3) plot using ggplot facet_wrap. However, the order of the subplots are not what I want.

My data and current plot:

df = data.frame(ID = rep(c(1:18),each=3), cluster = rep(c(1:6),each=9), 
            val = runif(54,5,8), date = rep(c(1:3),18))

ggplot(df, aes(date, val,)) + geom_bar(stat = 'identity') + 
            facet_wrap( ~ cluster*ID, nrow=3,ncol=6) + theme_bw()

enter image description here

However, as you can see, the plots are in order of the ID. What I want is to have each column as clusters (i.e. column 1 contains cluster 1 with ID 1,2,3; column 2 contains cluster 2 with ID 4,5,6 etc).

Is there anyway to do this? Please help! Thank you!


Solution

  • I think you just need to indicate the direction with dir

    ggplot(df, aes(date, val,)) + geom_bar(stat = 'identity') +
                facet_wrap(~cluster * ID, nrow = 3, ncol = 6, dir = "v") + theme_bw()
    

    enter image description here