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)
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()
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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With