How do I get ggplot to order facets correctly?
11,921
Solution 1
Without your data, my best guess would be to turn your faceting variable into a factor that has the levels in the order which you desire.
Solution 2
data$var <- factor(data$var, levels = sort(unique(data$var)))
Author by
Maiasaura
I'm research assistant professor at UC Berkeley. I use R extensively in my work and as part of a side project, develop R based tools to facilitate open, reproducible science (see http://ropensci.org).
Updated on July 26, 2022Comments
-
Maiasaura almost 2 years
I am trying to facet about 14 plots based on a variable that runs from 2-14. The plots show up in the order: 10,11,12,13,14,15,2,3,4,5,6,7,8,9
How do I get them to order from 2-15?
update: ok, so I made it a factor using
data$var=as.factor(data$var)
. The Levels areLevels: 10 11 12 13 14 15 2 3 4 5 6 7 8 9
How do I reorder those?
-
Maiasaura almost 14 yearsok, I figured out how to reorder levels. Thanks for pushing me in the right direction.
-
Maiasaura almost 14 yearsThe code, if anyone is interested is: data$var=factor(data$var, levels(data$var)[c(7:14,1:5)])
-
Pierre D almost 12 yearsand what's great is that you can also order facets in some predefined order. E.g.
f=c('Paul','Audrey','Marlene')
. Then simply sayd <- within(d, var <- factor(var, levels=f))
. -
calycolor almost 7 yearscan you give an example, please? i don't understand what d is above...i am trying to facet weekdays but ordered by an int of day of week (e.g., 1, 2, 3, 4, 5, 6, 7)
-
George D Girton almost 6 yearsfor calycolor: "d" above is the name of the data frame, called "data" in this example, so it would be, like "data <- within(data, var <- factor(var, levels =f)). ( If you are ordering a grouped variable, you have to apply the new levels before doing the grouping.) This facet ordering was hard for me to get, but this answer above is the one that helped.