Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change from row to column major order with facet_wrap?

Tags:

r

ggplot2

I want to make a 2x4 array of plots that show distributions changing over time. The default ggplot arrangement with facet_wrap is that the top row has series 1&2, the second row has series 3&4, etc. I would like to change this so that the first column has series in order (1->2->3->4) and then the second column has the next 4 series. This way your eye can compare immediately adjacent distributions in time vertically (as I think they should be).

like image 673
Evan Zamir Avatar asked Feb 22 '13 22:02

Evan Zamir


2 Answers

Use the direction dir parameter to facet_wrap(). Default is horizontal, and this can be switched to vertical:

# Horizontally
ggplot(mtcars, aes(x=hp, y=mpg)) + geom_point() + facet_wrap(~ cyl, ncol=2)

# Vertically
ggplot(mtcars, aes(x=hp, y=mpg)) + geom_point() + facet_wrap(~ cyl, ncol=2, dir="v")
like image 171
Megatron Avatar answered Oct 20 '22 00:10

Megatron


Looks like you need to do this with the ordering factor prior to the the facet_wrap call:

 fac <- factor( fac, levels=as.character(c(1, 10, 2, 20, 3, 30, 4, 40) ) )

The default for as/table in facet_wrap is TRUE which is going to put the lowest value ("1" in this case) at the upper left and the highest value ("40" in the example above) at the lower right corner. So:

 pl + facet_wrap(~fac, ncol=2, nrow=4)

Your comments suggest you are working with numeric class variables. (Your comments still do not provide a working example and you seem to think this is our responsibility and not yours. Where does one acquire such notions of entitlement?) This should create a factor that might be "column major" ordered with either numeric of factor input:

> ss <- 1:8; factor(ss, levels=ss[matrix(ss, ncol=2, byrow=TRUE)])
[1] 1 2 3 4 5 6 7 8
Levels: 1 3 5 7 2 4 6 8

On the other hand I can think of situations where this might be the effective approach:

> ss <- 1:8; factor(ss, levels=ss[matrix(ss, nrow=2, byrow=TRUE)])
[1] 1 2 3 4 5 6 7 8
Levels: 1 5 2 6 3 7 4 8
like image 42
IRTFM Avatar answered Oct 19 '22 23:10

IRTFM