'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)
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?
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |