12

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?

Community
  • 1
  • 1
DeltaIV
  • 4,773
  • 12
  • 39
  • 86

1 Answers1

8

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)
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • Brilliant! In my real case I mapped Case not only to the `color` aestethic but also to the `linetype` one. Thus thr other solutions would have forced mr to manually set the scale for `linetype` also. Your solution is simpler. Thanks! – DeltaIV Aug 08 '16 at 18:13