Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to reorder only the facets of facet_wrap, without reordering the underlying factor levels?

Sample data frame:

df <- data.frame(x=rep(1:10,4),y=rnorm(40),Case=rep(c("B","L","BC","R"),each=10))

I can plot each time series in its own facet with:

ggplot(df,aes(x=x,y=y,color=Case)) + geom_line()+facet_wrap(~Case,nr=2,nc=2)

enter image description here Now, suppose I want to change the facet order to (starting from top-left and going to bottom-right along rows) "L","B","R","BC". The usual suggestion here on SO is to do this. However, if I reorder the levels of factor Case, also the colors of the curves will be changed. Is it possible to reorder the facets, without changing also the order of the curve colors? I know it sounds like a weird question. The problem is that my report is a work in progress, and in a older version of the report, which I already showed to coworkers & management, there were multiple plots more or less like this (with no facet_wrap):

ggplot(df,aes(x=x,y=y,color=Case)) + geom_line()

enter image description here

In other words, by now people are used to associate the "B" to the red color. If I reorder, "L" will be red, "B" green, and so on. I can already hear the complaints...any way out of this one?

like image 955
DeltaIV Avatar asked Aug 08 '16 17:08

DeltaIV


1 Answers

Copy the data into a new column with the order you want. Use the new column for faceting, the old column for the the color.

df$facet = factor(df$Case, levels = c("L", "B", "R", "BC"))

ggplot(df, aes(x = x, y = y, color = Case)) + 
    geom_line() + 
    facet_wrap(~facet, nr = 2)
like image 185
Gregor Thomas Avatar answered Oct 22 '22 10:10

Gregor Thomas